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


当前回答

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

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

其他回答

改进安德烈斯·里奥里奥,处理任何数量的争论

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(...args) {
    var output = args.join(' ');
    log_file.write(util.format(output) + '\r\n');
    log_stdout.write(util.format(output) + '\r\n');
};

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

大多数记录器是过量的,不支持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.

我只是建立了一个包来做这个,希望你喜欢它;) https://www.npmjs.com/package/writelog

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