我是否可以配置console.log,以便将日志写入文件,而不是打印在控制台中?


当前回答

大多数记录器是过量的,不支持console.log中的正确构建。因此我创建了console-log-to-file:

import { consoleLogToFile } from "console-log-to-file";
// or `const { consoleLogToFile } = require("console-log-to-file/dist/index.cjs.js")`

consoleLogToFile({
  logFilePath: "/log/default.log",
});

// all of your console.log/warn/error/info will work as it does and save to file now.

其他回答

我经常使用很多参数console.log()和console.error(),所以我的解决方案是:

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 () {
  logFile.write(util.format.apply(null, arguments) + '\n');
  logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;

重写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;

如果你正在使用forever来保持节点应用程序运行,那么输入forever list将显示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

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

您现在可以使用Caterpillar,这是一个基于流的日志记录系统,允许您登录它,然后将输出输出到不同的转换和位置。

输出到一个文件很简单:

var logger = new (require('./').Logger)();
logger.pipe(require('fs').createWriteStream('./debug.log'));
logger.log('your log message');

卡特彼勒网站上的完整示例