我是否可以配置console.log,以便将日志写入文件,而不是打印在控制台中?
当前回答
你也可以重载默认的console.log函数:
var fs = require('fs');
var util = require('util');
var log_file = fs.createWriteStream(__dirname + '/debug.log', {flags : 'w'});
var log_stdout = process.stdout;
console.log = function(d) { //
log_file.write(util.format(d) + '\n');
log_stdout.write(util.format(d) + '\n');
};
上面的例子将记录到debug.log和stdout。
编辑:在本页上也可以看到Clément的多参数版本。
其他回答
如果你正在寻找生产中的东西,温斯顿可能是最好的选择。
如果你只是想快速完成开发工作,直接输出到文件中(我认为这只适用于*nix系统):
nohup node simple-server.js > output.log &
我采用了将输出流交换为我的流的想法。
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;
我自己简单地从温斯顿的例子,并添加了log(…)方法(因为温斯顿命名为info(..):
Console.js:
"use strict"
// Include the logger module
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
// Add log command
logger.log=logger.info;
module.exports = logger;
然后在代码中使用:
const console = require('Console')
现在你可以简单地在你的文件中使用正常的日志功能,它会创建一个文件并将其记录到你的控制台(在调试/开发时)。因为if (process.env。NODE_ENV !== 'production'){(如果你想让它也在生产环境中)…
您现在可以使用Caterpillar,这是一个基于流的日志记录系统,允许您登录它,然后将输出输出到不同的转换和位置。
输出到一个文件很简单:
var logger = new (require('./').Logger)();
logger.pipe(require('fs').createWriteStream('./debug.log'));
logger.log('your log message');
卡特彼勒网站上的完整示例
创建一个utils/logger.js文件:
var fs = require('fs');
var util = require('util');
var log_file = fs.createWriteStream(__dirname + '/../logs/server.log', { flags: 'w' });
var log_stdout = process.stdout;
console.log = function () { //
[...arguments].forEach(element => {
log_file.write(util.format(element) + '\n');
log_stdout.write(util.format(element) + '\n');
});
};
module.exports = {
console
}
将logger.js文件包含在你想要console.log的任何文件中,例如:
const console = require('./utils/logger').console;
创建一个logs文件夹,并在其中创建一个空的server.log文件,并运行你的应用程序:)
推荐文章
- 有没有办法修复包锁。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