我是否可以配置console.log,以便将日志写入文件,而不是打印在控制台中?
当前回答
另一个没有提到的解决方案是在进程中钩子可写流。Stdout和process.stderr。这样就不需要重写输出到stdout和stderr的所有控制台函数。这个实现将stdout和stderr重定向到一个日志文件:
var log_file = require('fs').createWriteStream(__dirname + '/log.txt', {flags : 'w'})
function hook_stream(stream, callback) {
var old_write = stream.write
stream.write = (function(write) {
return function(string, encoding, fd) {
write.apply(stream, arguments) // comments this line if you don't want output in the console
callback(string, encoding, fd)
}
})(stream.write)
return function() {
stream.write = old_write
}
}
console.log('a')
console.error('b')
var unhook_stdout = hook_stream(process.stdout, function(string, encoding, fd) {
log_file.write(string, encoding)
})
var unhook_stderr = hook_stream(process.stderr, function(string, encoding, fd) {
log_file.write(string, encoding)
})
console.log('c')
console.error('d')
unhook_stdout()
unhook_stderr()
console.log('e')
console.error('f')
它应该打印在控制台中
a
b
c
d
e
f
在日志文件中:
c
d
要了解更多信息,请查看以下要点。
其他回答
2013年更新-这是在Node v0.2和v0.4左右编写的;现在有关于日志的更好的实用程序。我强烈推荐温斯顿
2013年底更新-我们仍然使用温斯顿,但现在有一个记录器库来包装自定义对象和格式的日志记录功能。下面是logger.js https://gist.github.com/rtgibbons/7354879的一个示例
应该就是这么简单。
var access = fs.createWriteStream(dir + '/node.access.log', { flags: 'a' })
, error = fs.createWriteStream(dir + '/node.error.log', { flags: 'a' });
// redirect stdout / stderr
proc.stdout.pipe(access);
proc.stderr.pipe(error);
Winston是一个非常流行的用于日志记录的npm模块。
这里有一个操作指南。 在你的项目中安装温斯顿:
npm install winston --save
这里有一个现成的配置,我经常在我的项目中使用它作为utils下的logger.js。
/**
* Configurations of logger.
*/
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
const consoleConfig = [
new winston.transports.Console({
'colorize': true
})
];
const createLogger = new winston.Logger({
'transports': consoleConfig
});
const successLogger = createLogger;
successLogger.add(winstonRotator, {
'name': 'access-file',
'level': 'info',
'filename': './logs/access.log',
'json': false,
'datePattern': 'yyyy-MM-dd-',
'prepend': true
});
const errorLogger = createLogger;
errorLogger.add(winstonRotator, {
'name': 'error-file',
'level': 'error',
'filename': './logs/error.log',
'json': false,
'datePattern': 'yyyy-MM-dd-',
'prepend': true
});
module.exports = {
'successlog': successLogger,
'errorlog': errorLogger
};
然后在需要的地方导入,如下所示:
const errorLog = require('../util/logger').errorlog;
const successlog = require('../util/logger').successlog;
然后您可以将成功记录为:
successlog.info(`Success Message and variables: ${variable}`);
错误为:
errorlog.error(`Error Message : ${error}`);
它还将所有的成功日志和错误日志记录在logs目录下的一个文件中,如您在这里看到的那样。
const fs = require("fs");
const {keys} = Object;
const {Console} = console;
/**
* Redirect console to a file. Call without path or with false-y
* value to restore original behavior.
* @param {string} [path]
*/
function file(path) {
const con = path ? new Console(fs.createWriteStream(path)) : null;
keys(Console.prototype).forEach(key => {
if (path) {
this[key] = (...args) => con[key](...args);
} else {
delete this[key];
}
});
};
// patch global console object and export
module.exports = console.file = file;
要使用它,可以这样做:
require("./console-file");
console.file("/path/to.log");
console.log("write to file!");
console.error("also write to file!");
console.file(); // go back to writing to stdout
方法stdout和stderr
这种方法可以帮助您(我在我的项目中使用类似的方法),并且适用于所有方法,包括console.log、console。警告说,控制台。错误,console.info
该方法将写入stdout和stderr的字节写入文件。比更改console.log, console.log更好。警告说,控制台。错误,console.info方法,因为输出将与此方法的输出完全相同
var fs= require("fs")
var os= require("os")
var HOME= os.homedir()
var stdout_r = fs.createWriteStream(HOME + '/node.stdout.log', { flags: 'a' })
var stderr_r = fs.createWriteStream(HOME + '/node.stderr.log', { flags: 'a' })
var attachToLog= function(std, std_new){
var originalwrite= std.write
std.write= function(data,enc){
try{
var d= data
if(!Buffer.isBuffer(d))
d= Buffer.from(data, (typeof enc === 'string') ? enc : "utf8")
std_new.write.apply(std_new, d)
}catch(e){}
return originalwrite.apply(std, arguments)
}
}
attachToLog(process.stdout, stdout_r)
attachToLog(process.stderr, stderr_r)
// recommended catch error on stdout_r and stderr_r
// stdout_r.on("error", yourfunction)
// stderr_r.on("error", yourfunction)
我采用了将输出流交换为我的流的想法。
const LogLater = require ('./loglater.js');
var logfile=new LogLater( 'log'+( new Date().toISOString().replace(/[^a-zA-Z0-9]/g,'-') )+'.txt' );
var PassThrough = require('stream').PassThrough;
var myout= new PassThrough();
var wasout=console._stdout;
myout.on('data',(data)=>{logfile.dateline("\r\n"+data);wasout.write(data);});
console._stdout=myout;
var myerr= new PassThrough();
var waserr=console._stderr;
myerr.on('data',(data)=>{logfile.dateline("\r\n"+data);waserr.write(data);});
console._stderr=myerr;
loglater.js:
const fs = require('fs');
function LogLater(filename, noduplicates, interval) {
this.filename = filename || "loglater.txt";
this.arr = [];
this.timeout = false;
this.interval = interval || 1000;
this.noduplicates = noduplicates || true;
this.onsavetimeout_bind = this.onsavetimeout.bind(this);
this.lasttext = "";
process.on('exit',()=>{ if(this.timeout)clearTimeout(this.timeout);this.timeout=false; this.save(); })
}
LogLater.prototype = {
_log: function _log(text) {
this.arr.push(text);
if (!this.timeout) this.timeout = setTimeout(this.onsavetimeout_bind, this.interval);
},
text: function log(text, loglastline) {
if (this.noduplicates) {
if (this.lasttext === text) return;
this.lastline = text;
}
this._log(text);
},
line: function log(text, loglastline) {
if (this.noduplicates) {
if (this.lasttext === text) return;
this.lastline = text;
}
this._log(text + '\r\n');
},
dateline: function dateline(text) {
if (this.noduplicates) {
if (this.lasttext === text) return;
this.lastline = text;
}
this._log(((new Date()).toISOString()) + '\t' + text + '\r\n');
},
onsavetimeout: function onsavetimeout() {
this.timeout = false;
this.save();
},
save: function save() { fs.appendFile(this.filename, this.arr.splice(0, this.arr.length).join(''), function(err) { if (err) console.log(err.stack) }); }
}
module.exports = LogLater;
推荐文章
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在Ubuntu上安装Node.js
- 使用express.js代理
- Python日志记录不输出任何东西
- Node -使用NODE_MODULE_VERSION 51根据不同的Node.js版本编译
- RabbitMQ / AMQP:单队列,同一消息的多个消费者?
- IE9是否支持console.log,它是一个真实的功能吗?
- Node.js同步执行系统命令
- 禁用包的postinstall脚本
- Node.js上的html解析器
- 错误:无法找到模块“webpack”
- 有nginx access_log和error_log日志的STDOUT和STDERR的主进程
- 在node.js中使用async / await文件系统
- NodeJS -用NPM安装错误
- 如何为本地安装npm包设置自定义位置?