繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM