[英]node.js winston logging module - how to put timestamp at start of line instead of end
我的common.js文件中包含以下代碼:
var winston = require('winston');
winston.add(winston.transports.File, { 'timestamp':true, name:'log.error', filename: './app_error.log',level:'error', eol:'\n'});
winston.add(winston.transports.File, { 'timestamp':true, name:'log.warn', filename: './app_warn.log',level:'warn', eol:'\n'});
winston.add(winston.transports.File, { 'timestamp':true, name:'log.debug', filename: './app_debug.log',level:'debug', eol:'\n'});
文件的內容如下所示:
{“ level”:“ info”,“ message”:“ router.get()使用:10244嘗試dbquery”,“ timestamp”:“” 2016-10-26T20:51:21.428Z“}
{“ level”:“ info”,“ message”:“使用10244 callerid調用的hash_get()”,“ timestamp”:“” 2016-10-26T20:51:21.435Z“}
我想知道如何使時間戳成為該行的第一個字段,並且沒有單詞“ timestamp”。 像這樣的東西:
{“ 2016-10-26T20:51:21.428Z”,“ level”:“ info”,“ message”:“ router.get()嘗試使用:10244進行dbquery”}
編輯1
試圖將我的代碼更改為如下所示:
common.js
var winston = require('winston');
winston.add(winston.transports.File, {
'timestamp':function() {
return moment().format("YYYY-MM-DD HH:MM:SS");
},
name:'log.debug',
filename: './app_debug.log',
level:'debug',
eol:'\n',
formatter: function(options) {
// Return string will be passed to logger.
return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') +
(options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' );
}
});
exports.winston = winston;
路由器
var common = require('./common');
var winston = common.winston;
if (debug) { winston.log('info','router.get() query to db returned - ' + data); }
但是系統仍將時間戳記放在最后。
您可以添加一個自定義函數,該函數將格式化的日期返回到timestamp選項:
var moment = require('moment')
winston.add(winston.transports.File, {
'timestamp': function(){
return moment().format("YYYY-MM-DD");
},
name:'log.error',
filename: './app_error.log',
level:'error',
eol:'\n'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.