node.js 节点:登录文件而不是控制台

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8393636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:51:35  来源:igfitidea点击:

Node: log in a file instead of the console

node.js

提问by Randomblue

Can I configure console.logso that the logs are written on a file instead of being printed in the console?

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

采纳答案by Ryan Gibbons

Update 2013 -This was written around Node v0.2 and v0.4; There are much better utilites now around logging. I highly recommend Winston

2013 年更新 -这是围绕 Node v0.2 和 v0.4 编写的;现在有更好的工具来记录日志。我强烈推荐温斯顿

Update Late 2013 -We still use winston, but now with a logger library to wrap the functionality around logging of custom objects and formatting. Here is a sample of our logger.js https://gist.github.com/rtgibbons/7354879

2013 年末更新 -我们仍然使用 winston,但现在使用一个记录器库来包装自定义对象和格式记录的功能。这是我们的 logger.jshttps://gist.github.com/rtgibbons/7354879的示例



Should be as simple as this.

应该就这么简单。

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);

回答by ceeroover

You could also just overload the default console.log function:

你也可以重载默认的 console.log 函数:

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(d) { //
  log_file.write(util.format(d) + '\n');
  log_stdout.write(util.format(d) + '\n');
};

Above example will log to debug.log and stdout.

上面的例子将记录到 debug.log 和 stdout。

Edit:See multiparameter version by Clémentalso on this page.

编辑:也可在此页面上查看 Clément 的多参数版本

回答by alessioalex

If you are looking for something in production winstonis probably the best choice.

如果您正在寻找生产中的东西,winston可能是最佳选择。

If you just want to do dev stuff quickly, output directly to a file (I think this works only for *nix systems):

如果您只想快速完成开发工作,请直接输出到文件(我认为这仅适用于 *nix 系统):

nohup node simple-server.js > output.log &

回答by Clément Désiles

I often use many arguments to console.log()and console.error(), so my solution would be:

我经常对console.log()console.error()使用许多参数,所以我的解决方案是:

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 () {
  logFile.write(util.format.apply(null, arguments) + '\n');
  logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;

回答by keshavDulal

Winstonis a very-popular npm-module used for logging.

Winston是一个非常流行的用于日志记录的 npm 模块。

Here is a how-to.
Install winston in your project as:

这是一个操作方法。
在您的项目中安装 winston 为:

npm install winston --save

Here's a configuration ready to use out-of-box that I use frequently in my projects as logger.js under utils.

这是一个准备好开箱即用的配置,我在我的项目中经常使用它作为 utils 下的 logger.js。

 /**
 * Configurations of logger.
 */
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');

const consoleConfig = [
  new winston.transports.Console({
    'colorize': true
  })
];

const createLogger = new winston.Logger({
  'transports': consoleConfig
});

const successLogger = createLogger;
successLogger.add(winstonRotator, {
  'name': 'access-file',
  'level': 'info',
  'filename': './logs/access.log',
  'json': false,
  'datePattern': 'yyyy-MM-dd-',
  'prepend': true
});

const errorLogger = createLogger;
errorLogger.add(winstonRotator, {
  'name': 'error-file',
  'level': 'error',
  'filename': './logs/error.log',
  'json': false,
  'datePattern': 'yyyy-MM-dd-',
  'prepend': true
});

module.exports = {
  'successlog': successLogger,
  'errorlog': errorLogger
};

And then simply import wherever required as this:

然后只需在需要的地方导入,如下所示:

const errorLog = require('../util/logger').errorlog;
const successlog = require('../util/logger').successlog;

Then you can log the success as:

然后您可以将成功记录为:

successlog.info(`Success Message and variables: ${variable}`);

and Errors as:

和错误为:

errorlog.error(`Error Message : ${error}`);

It also logs all the success-logs and error-logs in a file under logs directory date-wise as you can see here.
log direcotry

它还按日期将所有成功日志和错误日志记录在日志目录下的文件中,如您所见。
日志目录

回答by rich remer

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;

To use it, do something like:

要使用它,请执行以下操作:

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

回答by Marco

If this is for an application, you're probably better off using a logging module. It'll give you more flexibility. Some suggestions.

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

回答by reliasn

Another solution not mentioned yet is by hooking the Writablestreams in process.stdoutand process.stderr. This way you don't need to override all the console functionsthat output to stdout and stderr. This implementation redirects both stdout and stderr to a log file:

另一个尚未提及的解决方案是将Writable流挂在process.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')

It should print in the console

它应该在控制台中打印

a
b
c
d
e
f

and in the log file:

并在日志文件中:

c
d

For more info, check this gist.

有关更多信息,请查看此要点

回答by SridharKritha

For simple cases, we could redirect the Standard Out (STDOUT) and Standard Error (STDERR)streams directly to file by '>'and '2>&1'

对于简单的情况,我们可以通过'>''2>&1'标准输出 (STDOUT) 和标准错误 (STDERR)流直接重定向到文件

Example:

例子:

// test.js
(function() {
    // Below outputs are sent to Standard Out (STDOUT) stream
    console.log("Hello Log");
    console.info("Hello Info");
    // Below outputs are sent to Standard Error (STDERR) stream
    console.error("Hello Error");
    console.warn("Hello Warning");
})();

node test.js > test.log 2>&1

节点 test.js > test.log 2>&1

As per the POSIX standard, 'input', 'output' and 'error'streams are identified by the positive integer file descriptors(0, 1, 2). i.e., stdin is 0, stdout is 1, and stderr is 2.

根据 POSIX 标准,“输入”、“输出”和“错误”流由正整数文件描述符(0、1、2)标识。即,stdin 为 0,stdout 为 1,stderr 为 2。

'2>&1'will redirect from 2 (stderr) to 1 (stdout)

'>'will redirect from 1 (stdout) to file (test.log)

'2>&1'将从 2 (stderr) 重定向到 1 (stdout)

'>'将从 1 (stdout) 重定向到文件 (test.log)

回答by Simon Rigét

Overwriting console.log is the way to go. But for it to work in required modules, you also need to export it.

覆盖 console.log 是要走的路。但是为了让它在所需的模块中工作,您还需要导出它。

module.exports = console;

To save yourself the trouble of writing log files, rotating and stuff, you might consider using a simple logger module like winston:

为了省去编写日志文件、旋转等的麻烦,你可以考虑使用一个简单的记录器模块,比如 winston:

// 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;