我是否可以配置console.log,以便将日志写入文件,而不是打印在控制台中?
当前回答
基于多参数版本的Clément,只是没有颜色代码的文本文件
var fs = require('fs');
var util = require('util');
var logFile = fs.createWriteStream('log.txt', { flags: 'a' });
// Or 'w' to truncate the file every time the process starts.
var logStdout = process.stdout;
console.log = function () {
// Storing without color codes
logFile.write(util.format.apply(null,arguments).replace(/\033\[[0-9;]*m/g,"") + '\n');
// Display normally, with colors to Stdout
logStdout.write(util.format.apply(null, arguments) + '\n');
}
注:回答因为我不能评论
其他回答
重写console.log是正确的方法。但是要让它在所需的模块中工作,还需要导出它。
module.exports = console;
为了节省自己写日志文件的麻烦,旋转和东西,你可以考虑使用一个简单的记录器模块,如温斯顿:
// Include the logger module
var winston = require('winston');
// Set up log file. (you can also define size, rotation etc.)
winston.add(winston.transports.File, { filename: 'somefile.log' });
// Overwrite some of the build-in console functions
console.error = winston.error;
console.log = winston.info;
console.info = winston.info;
console.debug = winston.debug;
console.warn = winston.warn;
module.exports = console;
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);
对于未来的用户。@keshavDulal答案不适用于最新版本。而且我无法找到针对最新版本3.3.3中报告的问题的适当修复。
不管怎样,在研究了一下之后,我终于把它修好了。下面是温斯顿3.3.3版本的解决方案
安装winston和winston-daily-rotate-file
npm install winston
npm install winston-daily-rotate-file
创建一个新文件utils/logger.js
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
var logger = new winston.createLogger({
transports: [
new (winston.transports.DailyRotateFile)({
name: 'access-file',
level: 'info',
filename: './logs/access.log',
json: false,
datePattern: 'yyyy-MM-DD',
prepend: true,
maxFiles: 10
}),
new (winston.transports.DailyRotateFile)({
name: 'error-file',
level: 'error',
filename: './logs/error.log',
json: false,
datePattern: 'yyyy-MM-DD',
prepend: true,
maxFiles: 10
})
]
});
module.exports = {
logger
};
然后在任何你想要使用日志导入模块的文件
const logger = require('./utils/logger').logger;
像下面这样使用记录器:
logger.info('Info service started');
logger.error('Service crashed');
另一个没有提到的解决方案是在进程中钩子可写流。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
要了解更多信息,请查看以下要点。
如果这是针对应用程序的,那么最好使用日志记录模块。这会给你更多的灵活性。一些建议。
·温斯顿https://github.com/winstonjs/winston log4js https://github.com/nomiddlename/log4js-node
推荐文章
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- 如何使用npm全局安装一个模块?
- 如何在SQL Server Management Studio中查看查询历史
- 实时http流到HTML5视频客户端的最佳方法
- 使用node.js下载图像
- Node.js Express中的HTTP GET请求
- Node.js:将文本文件读入数组。(每一行都是数组中的一项。)
- Python中带有回溯的日志异常
- npm犯错!错误:EPERM:操作不允许,重命名
- Node Sass还不支持当前环境:Linux 64位,带false
- 我如何添加环境变量启动。VSCode中的json
- 解析错误:无法读取文件“…/tsconfig.json”.eslint
- 在Node.js中'use strict'语句是如何解释的?
- 当WebSockets可用时,为什么要使用AJAX ?
- 使用过程。TypeScript中的env