winston日志管理2
上次讲到
Exceptions 例外
Handling Uncaught Exceptions with winston 使用winston处理未捕获的异常(这个如果对于异步,我不是很喜欢用)
使用winston,可以从进程捕获和记录uncaughtException事件。 有两种不同的方式通过默认的winston logger或者你自己的logger实例启用这个功能。
Logging Levels 日志级别
每个级别都有一个特定的整数优先级。 优先级越高,消息被认为越重要,并且相应的整数优先级越低。 例如,npm日志记录级别的优先级从0到5(从最高到最低):
{ error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 }
Similarly, as specified exactly in RFC5424 the syslog
levels are prioritized from 0 to 7 (highest to lowest).
{ emerg: 0, alert: 1, crit: 2, error: 3, warning: 4, notice: 5, info: 6, debug: 7 }
If you do not explicitly define the levels that winston
should use the npm
levels above will be used.
Using Logging Levels 使用logging level
Setting the level for your logging message can be accomplished in one of two ways. You can pass a string representing the logging level to the log() method or use the level specified methods defined on every winston Logger.
设置记录消息的级别可以通过两种方式之一完成。 您可以将表示日志记录级别的字符串传递给log()方法,或者使用在每个winston Logger上定义的级别指定方法。
// // Any logger instance // logger.log('silly', "127.0.0.1 - there's no place like home"); logger.log('debug', "127.0.0.1 - there's no place like home"); logger.log('verbose', "127.0.0.1 - there's no place like home"); logger.log('info', "127.0.0.1 - there's no place like home"); logger.log('warn', "127.0.0.1 - there's no place like home"); logger.log('error', "127.0.0.1 - there's no place like home"); logger.info("127.0.0.1 - there's no place like home"); logger.warn("127.0.0.1 - there's no place like home"); logger.error("127.0.0.1 - there's no place like home");
使用logger.info的方式,或者使用logger.log('info')winston
allows you to define alevel
property on each transport which specifies the maximum level of messages that a transport should log. For example, using thenpm
levels you could log onlyerror
messages to the console and everythinginfo
and below to a file (which includeserror
messages):
winston允许您在每个传输上定义一个level属性,它指定传输应该记录的最大消息级别。 例如,使用npm级别,您可以只记录到控制台的错误消息以及下面的一切信息到文件(其中包括错误消息):
var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ level: 'error' }), new (winston.transports.File)({ filename: 'somefile.log', level: 'info' }) ] });
所有大于error级别的都会在console上显示,而在info上,所有大于info级别的都会写到somefile.log
Using Custom Logging Levels 使用传统的log 级别
In addition to the predefined npm and syslog levels available in Winston, you can also choose to define your own:
除了Winston中提供的预定义的npm和syslog级别之外,您还可以选择定义自己的:
var myCustomLevels = { levels: { foo: 0, bar: 1, baz: 2, foobar: 3 }, colors: { foo: 'blue', bar: 'green', baz: 'yellow', foobar: 'red' } }; var customLevelLogger = new (winston.Logger)({ levels: myCustomLevels.levels }); customLevelLogger.foobar('some foobar level-ed message');
对于winston添加颜色的设置:
winston.addColors(myCustomLevels.colors);一般会在打印的时候使用.