如何使用Node.js库Winston向日志添加时间戳?
问题描述:
我想在日志中添加时间戳.实现此目标的最佳方法是什么?
I want to add timestamp to logs. What is the best way to achieve this?
答
我自己正在处理同一问题.我有两种方法可以做到这一点.
I was dealing with the same issue myself. There are two ways I was able to do this.
包括Winston时,通常默认情况下添加控制台传输.为了使时间戳在这种默认情况下可以正常工作,我需要:
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:
- 删除控制台传输,并使用timestamp选项再次添加.
- 使用timestamp选项设置为true创建您自己的Logger对象.
第一个:
var winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp':true});
第二个更清洁的选项:
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({'timestamp':true})
]
});
可以在此处找到其他一些用于控制台传输的选项. >:
- level:此传输应记录的消息级别(默认为"debug").
- silent:布尔值标志,指示是否抑制输出(默认为false).
- colorize:布尔型标志,指示是否应为输出着色(默认为false).
- timestamp:布尔型标志,指示是否应在输出之前加上时间戳(默认为false).如果指定了function,则将使用其返回值代替时间戳.