拦截控制台日志到文件Nodejs

Intercept console logs to file Nodejs

我正在使用 NodeJs 开发游戏,并意识到访问旧的 console.log 输出将非常有帮助。机制和计算变得相当复杂,如果以后能够访问它们以搜索并对它们进行一些数据分析以找到我的修改器(战斗机制)的正确值,那就太好了。同时,我也想在控制台中看到 console.log


我知道这对于常规 javascript 是不可能的(参见 This),但我希望 npm 有一些方法可以拦截日志并将它们记录到文件中服务器。有什么想法吗?

你可以像这样拦截console.log

var cl = console.log

console.log = function(...args){
  // your custom logging logic here
  cl.apply(console, args)
}

同时记录到标准输出和文件的 NPM 选项可以是 Winston. Winston is a logging library that allows you to define your own loggers, specifying their transports (a transport being what do you do with these log lines). In your case, you could define a logger with two transports, stdout and a log file. Example (inspired by the Winston documentation):

const winston = require('winston');

let logger = new (winston.Logger)({
    transports: [
        new (winston.transports.Console)(),
        new (winston.transports.File)({ filename: 'somefile.log' })
    ]
});

logger.info('hello, world!');

如果您 运行 上述代码,您将在控制台和 somefile.log.

中看到日志