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


当前回答

如果您正在寻找不修改任何代码的解决方案,这里有一个简单的解决方案。

它需要pm2,只需将它添加到你的节点模块,并启动你的应用程序

pm2 start server.js

你完成了,控制台。日志现在自动注册在home/.pm2/ Logs /server-out.log下。

其他回答

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

如果您正在寻找不修改任何代码的解决方案,这里有一个简单的解决方案。

它需要pm2,只需将它添加到你的节点模块,并启动你的应用程序

pm2 start server.js

你完成了,控制台。日志现在自动注册在home/.pm2/ Logs /server-out.log下。

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

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

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