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


当前回答

你也可以看看这个npm模块: https://www.npmjs.com/package/noogger

努格

简单直接……

其他回答

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

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

输出到一个文件很简单:

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

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

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

对于未来的用户。@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

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