node.js winston日志记录模块 - 如何将时间戳放在行的开头而不是结束

时间:2016-10-26 21:09:01

标签: javascript node.js winston

我在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()尝试dbquery使用:10244",& #34;时间戳":" 2016-10-26T20:51:21.428Z"}

     

{" level":" info"," message":" hash_get()使用10244 callerid","时间戳":" 2016-10-26T20:51:21.435Z"}

我想知道如何将时间戳作为该行中的第一个字段,而没有" timestamp"这个词。 像这样的东西:

  

{" 2016-10-26T20:51:21.428Z"," level":" info"," message":& #34; router.get()尝试使用dbquery:10244"}

编辑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); }

但系统仍然将时间戳放在最后。

1 个答案:

答案 0 :(得分:-1)

您可以添加一个自定义函数,该函数将格式化日期返回到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'
});