First use the nodeJS standard file system module FS:
const fs = require('fs');
Copy the code
Logs are usually time-stamped, so import the timestamp tool:
const dateTime = require('node-datetime');
Copy the code
Write to the log file of this article according to different log levels:
var log = {
setName:function(message) {
logName = message;
},
all:function(message){
console.log(getDate() + ' [ ALL - '+prepareLogName()+'] '+ message);
writeMessage(getDate() + ' [ ALL - '+prepareLogName()+'] '+ message);
},
trace:function(message){
console.log(getDate() + ' [ TRACE - '+prepareLogName()+'] '+ message);
writeMessage(getDate() + ' [ TRACE - '+prepareLogName()+'] '+ message);
},
debug:function(message){
console.log(getDate() + ' [ DEBUG - '+prepareLogName()+'] '+ message);
writeMessage(getDate() + ' [ DEBUG - '+prepareLogName()+'] '+ message);
},
info:function(message){
debugger;
console.log(getDate() + ' [ INFO - '+prepareLogName()+'] '+ message);
writeMessage(getDate() + ' [ INFO - '+prepareLogName()+'] '+ message);
},
warn:function(message){
console.log(getDate() + ' [ WARN - '+prepareLogName()+'] '+ message);
writeMessage(getDate() + ' [ WARN - '+prepareLogName()+'] '+ message);
},
error:function(message){
console.log(getDate() + ' [ ERROR - '+prepareLogName()+'] '+ message);
writeMessage(getDate() + ' [ ERROR - '+prepareLogName()+'] '+ message);
},
fatal:function(message){
console.log(getDate() + ' [ FATAL - '+prepareLogName()+'] '+ message);
writeMessage(getDate() + ' [ FATAL - '+prepareLogName()+'] '+ message);
},
off:function(message){
console.log(getDate() + ' [ OFF - '+prepareLogName()+'] '+ message);
writeMessage(getDate() + ' [ OFF - '+prepareLogName()+'] '+ message); }}Copy the code
The writeMessage method is implemented by calling fs to write to the local log file synchronously:
function writeMessage(message) {
pwd = process.cwd();
fs.appendFileSync(pwd+'/logs/log', message+"\n");
}
Copy the code
The last local log file to be written is shown below:
For more of Jerry’s original articles, please follow the public account “Wang Zixi “: