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


当前回答

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

其他回答

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

这里有一个操作指南。 在你的项目中安装温斯顿:

npm install winston --save

这里有一个现成的配置,我经常在我的项目中使用它作为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
};

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

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

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

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

错误为:

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

它还将所有的成功日志和错误日志记录在logs目录下的一个文件中,如您在这里看到的那样。

你可以使用nodejs的Console构造函数

const mylog = new console.Console(
  fs.createWriteStream("log/logger.log"),
  fs.createWriteStream("log/error.log")
);

然后你就可以像使用普通的控制台类一样使用它了,例如:

mylog.log("Ok!"); // Will be written into 'log/logger.log'
mylog.error("Bad!"); // Will be written into 'log/error.log'

除了上面的答案之外,还对覆盖console.log的简短而有效的代码进行了一点扩展。小增加:设置文件名与日期,包装功能,也做原来的控制台。日志记录以保持控制台使用该信息处于活动状态。

用法:在代码的开头,运行setConsoleLogToFile([FILENAME])。

const fs = require("fs"),
    util = require('util');


const getPrettyDate = ()=> new Date().toString().replace(":","-").replace(/00\s\(.*\)/, "").replace(` ${new Date().getFullYear()}`, ",").replace(/:\d\d\s/, " ");

module.exports.getPrettyDate = getPrettyDate;

module.exports.setConsoleLogToFile = (filename) => {
    const log_file = fs.createWriteStream(`${__dirname}/${filename} -  ${getPrettyDate()}.log`, { flags: 'w' }),
        log_stdout = process.stdout;

    const origConsole = console.log;
    console.log = (d) => { 
        origConsole(d);
        log_file.write(util.format(d) + '\n');
        log_stdout.write(util.format(d) + '\n');
    };
}

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

直接来自控制台的nodejs API文档

const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
const count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5