【问题标题】:Winston - Timestamp not addedWinston - 未添加时间戳
【发布时间】:2019-01-25 17:51:00
【问题描述】:

我正在使用 Winston 作为 NodeJS 项目的记录器。我尝试为日志消息添加时间戳并配置 Winston 以非 Json 方式编写控制台日志消息,但未成功。我的配置如下

const appRoot = require('app-root-path');
const winston = require('winston');

const options = {
    file: {
        level: 'info',
        filename: `${appRoot}/logs/app.log`,
        timestamp: true,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 15,
        colorize: false,
    },
    console: {
        level: 'debug',
        timestamp: true,
        handleExceptions: true,
        json: false,
        colorize: true,
    },
};

const logger = winston.createLogger({
    transports: [
        new winston.transports.File(options.file),
        new winston.transports.Console(options.console)
    ],
    exitOnError: false,
});

module.exports = logger;

这就是我在其他文件中导入 Winston 的方式(winston 配置文件位于我项目的根目录):

const winston = require('../winston');

知道它为什么起作用吗?

【问题讨论】:

    标签: node.js logging winston


    【解决方案1】:

    这是一个带时间戳的工作 winston 记录器模块:

    const { createLogger, format, transports } = require("winston");
    const { combine, timestamp, label, printf } = format;
    const appRoot = require("app-root-path");
    
    const myFormat = printf(({ level, message, label, timestamp }) => {
        return `${timestamp} ${level}: ${message}`;
    });
    
    const options = {
        file: {
            level: "info",
            filename: `${appRoot}/logs/app.log`,
            handleExceptions: true,
            json: true,
            maxsize: 5242880, // 5MB
            maxFiles: 5,
            colorize: false,
            timestamp: true,
        },
        console: {
            level: "debug",
            handleExceptions: true,
            json: false,
            colorize: true,
        },
    };
    const logger = createLogger({
        format: combine(label({ label: this.level }), timestamp(), myFormat),
        transports: [new transports.Console(options.console), new transports.File(options.file)],
    });
    
    module.exports = logger;
    
    

    【讨论】:

    • const options 很奇怪,以后只使用 options.file
    • 刚刚更新了示例以包含 options.console 道具 :)
    【解决方案2】:

    这是一个帮助在输出(日志文件、控制台)上打印时间戳的示例。

    本示例使用的版本:

    ├── express@4.17.1 ├── express-async-errors@3.1.1 └──winston@3.3.3

    // Declare winston
    const winston = require("winston");
    // Import all needed using Object Destructuring
    const { createLogger, format, transports } = require("winston");
    const { combine, timestamp, printf } = format;
    // Export the module
    module.exports = function (err, req, res, next) {
    
    
      const logger = createLogger({
        level: "error",
        format: combine(
          format.errors({ stack: true }), // log the full stack
          timestamp(), // get the time stamp part of the full log message
          printf(({ level, message, timestamp, stack }) => { // formating the log outcome to show/store 
            return `${timestamp} ${level}: ${message} - ${stack}`;
          })
        ),
        transports: [
          new transports.Console(), // show the full stack error on the console
          new winston.transports.File({ // log full stack error on the file
            filename: "logfile.log",
            format: format.combine(
              format.colorize({
                all: false,
              })
            ),
          }),
        ],
      });
    
      logger.log({
        level: "error",
        message: err,
      });
      // Response sent to client but nothing related to winston
      res.status(500).json(err.message);
    };
    

    【讨论】:

      【解决方案3】:

      winston 3 出现此错误。请查看this section 中指定记录器格式的文档。这将解决问题。

      【讨论】:

      • 我仍然无法在winston中添加时间戳。
      猜你喜欢
      • 2012-05-03
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 2013-12-09
      • 2019-10-19
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多