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

注:回答因为我不能评论

其他回答

基于多参数版本的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

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

2013年更新-这是在Node v0.2和v0.4左右编写的;现在有关于日志的更好的实用程序。我强烈推荐温斯顿

2013年底更新-我们仍然使用温斯顿,但现在有一个记录器库来包装自定义对象和格式的日志记录功能。下面是logger.js https://gist.github.com/rtgibbons/7354879的一个示例


应该就是这么简单。

var access = fs.createWriteStream(dir + '/node.access.log', { flags: 'a' })
      , error = fs.createWriteStream(dir + '/node.error.log', { flags: 'a' });

// redirect stdout / stderr
proc.stdout.pipe(access);
proc.stderr.pipe(error);
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