上次講到
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);一般會在打印的時候使用.