我是否可以配置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');
}

注:回答因为我不能评论

其他回答

如果这是针对应用程序的,那么最好使用日志记录模块。这会给你更多的灵活性。一些建议。

·温斯顿https://github.com/winstonjs/winston log4js https://github.com/nomiddlename/log4js-node

另一个没有提到的解决方案是在进程中钩子可写流。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

要了解更多信息,请查看以下要点。

你可以使用nodejs的Console构造函数

const mylog = new console.Console(
  fs.createWriteStream("log/logger.log"),
  fs.createWriteStream("log/error.log")
);

然后你就可以像使用普通的控制台类一样使用它了,例如:

mylog.log("Ok!"); // Will be written into 'log/logger.log'
mylog.error("Bad!"); // Will be written into 'log/error.log'

如果你正在使用forever来保持节点应用程序运行,那么输入forever list将显示console.log正在写入的日志文件的路径

如果您正在使用linux,您还可以使用输出重定向。Windows就不太确定了。

node server.js >> file.log 2>> file.log

>> file.log将标准输出重定向到文件

2>> file.log将stderr重定向到文件

其他人使用速记&>>作为stdout和stderr,但它不被我的MAC和ubuntu接受:(

额外:>覆盖,>>追加。

顺便说一下,关于NodeJS日志记录器,我使用pino + pino-pretty logger