如何使用 Node.js 库 Winston 向日志添加时间戳?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10271373/
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 15:35:02  来源:igfitidea点击:

How can I add timestamp to logs using Node.js library Winston?

node.jsloggingwinston

提问by kolrie

I want to add timestamp to logs. What is the best way to achieve this?

我想在日志中添加时间戳。实现这一目标的最佳方法是什么?

回答by imagreenplant

I was dealing with the same issue myself. There are two ways I was able to do this.

我自己也在处理同样的问题。我有两种方法可以做到这一点。

When you include Winston, it usually defaults to adding a Console transport. In order to get timestamps to work in this default case, I needed to either:

当您包含 Winston 时,它通常默认添加控制台传输。为了让时间戳在这种默认情况下工作,我需要:

  1. Remove the console transport and add again with the timestamp option.
  2. Create your own Logger object with the timestamp option set to true.
  1. 删除控制台传输并使用时间戳选项再次添加。
  2. 创建您自己的 Logger 对象,并将时间戳选项设置为 true。

The first:

首先:

var winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp':true});

The second, and cleaner option:

第二个,更干净的选择:

var winston = require('winston');
var logger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)({'timestamp':true})
    ]
});

Some of the other options for Console transport can be found here:

可以在此处找到控制台传输的其他一些选项:

  • level: Level of messages that this transport should log (default 'debug').
  • silent: Boolean flag indicating whether to suppress output (default false).
  • colorize: Boolean flag indicating if we should colorize output (default false).
  • timestamp: Boolean flag indicating if we should prepend output with timestamps (default false). If function is specified, its return value will be used instead of timestamps.
  • 级别:此传输应记录的消息级别(默认为“调试”)。
  • 静默:布尔标志,指示是否抑制输出(默认为 false)。
  • colorize:布尔标志,指示我们是否应该对输出进行着色(默认为 false)。
  • 时间戳:布尔标志,指示我们是否应该在输出前加上时间戳(默认为 false)。如果指定了函数,则将使用其返回值而不是时间戳。

回答by Siva Kiran

Above answers did not work for me. In case you are trying to add timestamp to your logs using the latest version of Winston - 3.0.0-rc1, this worked like charm:

以上答案对我不起作用。如果您尝试使用最新版本的 Winston - 3.0.0-rc1 向日志添加时间戳,这就像魅力一样:

    const {transports, createLogger, format} = require('winston');

    const logger = createLogger({
        format: format.combine(
            format.timestamp(),
            format.json()
        ),
        transports: [
            new transports.Console(),
            new transports.File({filename: 'logs/error/error.log', level: 'error'}),
            new transports.File({filename: 'logs/activity/activity.log', level:'info'})
        ]
    });

I used 'format.combine()'. Since I needed timestamp on all my transports, I added the formatting option within the createLogger, rather than inside each transport. My output on console and on file (activity.log) are as follows:

我使用了'format.combine()'。因为我需要所有传输的时间戳,所以我在 createLogger 中添加了格式化选项,而不是在每个传输中。我在控制台和文件(activity.log)上的输出如下:

{"message":"Connected to mongodb","level":"info","timestamp":"2018-02-01T22:35:27.758Z"}
{"message":"Connected to mongodb","level":"info","timestamp":"2018-02-01T22:35:27.758Z"}

We can add formatting to this timestamp in 'format.combine()' as usual using:

我们可以像往常一样在 'format.combine()' 中为这个时间戳添加格式:

format.timestamp({format:'MM-YY-DD'})

回答by Biswadev

We can do like this also

我们也可以这样做

var winston = require('winston');
    const { createLogger, format, transports } = require('winston')
    var config = require('../configurations/envconfig.js');

    var loggerLevel = process.env.LOGGERLEVEL ||  config.get('LOGGERLEVEL');

    var logger = winston.createLogger({ format: format.combine(
            format.timestamp({
                format: 'YYYY-MM-DD HH:mm:ss'
            }),
            format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`+(info.splat!==undefined?`${info.splat}`:" "))
        ), 
        transports: [
            new (winston.transports.Console)({ level: loggerLevel }),
           ]
    });
    module.exports = logger;

回答by KTU

You can use built-in utiland foreverto achieve logging with timestap for your nodejs server. When you start a server add log output as part of the parameter:

您可以使用内置的util永远为您的 nodejs 服务器实现带时间戳的日志记录。当您启动服务器时,将日志输出添加为参数的一部分:

forever start -ao log/out.log server.js

And then you can write util in your server.js

然后你可以在你的 server.js 中编写 util

server.js

服务器.js

var util = require('util');
util.log("something with timestamp");

The output will look something like this to out.log file:

out.log 文件的输出将如下所示:

out.log

输出日志

15 Mar 15:09:28 - something with timestamp

回答by Tamil

Although I'm not aware of winston, this is a suggestion. I use log4jsfor logging & my logs by default look like this

虽然我不知道温斯顿,但这是一个建议。我使用log4js进行日志记录,默认情况下我的日志看起来像这样

[2012-04-23 16:36:02.965] [INFO] Development - Node Application is running on port 8090
[2012-04-23 16:36:02.966] [FATAL] Development - Connection Terminated to  '127.0.0.1' '6379'

Development is the environment of my node process & [INFO|FATAL] is log level

开发是我节点进程的环境&[INFO|FATAL]是日志级别

Maintaining different profiles for logging is possible in log4js. I have Development & Production profiles. Also there are logger types like rolling file appender, console appender, etc. As a addon your log files will be colorful based on the log level [Trace, Info, Debug, Error, Fatal] ;)

在 log4js 中可以维护不同的日志记录配置文件。我有开发和生产配置文件。还有记录器类型,如滚动文件附加程序、控制台附加程序等。作为插件,您的日志文件将根据日志级别 [Trace、Info、Debug、Error、Fatal] 变得丰富多彩;)

log4js will override your console.logIt is a configurable parameter now in 0.5+

log4js 将覆盖您的 console.log它现在是 0.5+ 中的可配置参数

回答by khoi nguyen

we could use console-stamp to add timestamp and log level to the existing console: require('console-stamp')(console, '[yyyy-mm-dd HH:MM:ss.l]')

我们可以使用 console-stamp 将时间戳和日志级别添加到现有控制台: require('console-stamp')(console, '[yyyy-mm-dd HH:MM:ss.l]')

See https://github.com/starak/node-console-stampfor the details

有关详细信息,请参阅https://github.com/starak/node-console-stamp

回答by walv

Sometimes default timestamp format can be not convenient for you. You can override it with your implementation.

有时默认时间戳格式对您来说可能不方便。您可以使用您的实现覆盖它。

Instead of

代替

var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
  new (winston.transports.Console)({'timestamp':true})
]
});

you can write

你可以写

var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
  new (winston.transports.Console)({
     'timestamp': function() {
        return <write your custom formatted date here>;
     }
  })
]
});

See https://github.com/winstonjs/winston#custom-log-formatfor the details

有关详细信息,请参阅https://github.com/winstonjs/winston#custom-log-format

回答by Renan Coelho

Another solution is wrapping the logger into a file that exports some functions like logger.info(), logger.error(), etc. then you just pass an extra key to be sent on every message log.

另一种解决方案是将记录器包装到一个文件中,该文件导出一些函数,如 logger.info()、logger.error() 等,然后您只需传递一个额外的密钥即可在每个消息日志上发送。

loggerService.js

记录器服务.js

const logger = winston.createLogger({ ... })

function handleLog(message, level) {
  const logData = {
    timestamp: Date.now(),
    message,
  }

  return logger[level](logData)
}

function info(message) {
  handleLog(message, 'info')
}

function error(message) {
  handleLog(message, 'error')
}

function warn(message) {
  handleLog(message, 'warn')
}

module.exports = {
  info,
  error,
  warn
}

whatever-file.js

任何文件.js

const logger = require('./services/loggerService')

logger.info('Hello World!')

your-log.log

你的日志

{"timestamp":"2019-08-21 06:42:27","message":"Hello World!","level":"info"}