如何使用节点js

时间:2017-05-24 10:59:07

标签: node.js date configuration log4js-node

我正在尝试将此日期时间格式[2017-05-23 12:05:37.327]的日志时间更改为这个23-May-17 12:05:37。 我正在使用这个包: https://www.npmjs.com/package/log4js

这是node4js的文件配置。

     {
       "appenders": [
      {

        "type": "file",
       "filename": "logs/v_1_0_9.log",
       "maxLogSize":1073741824,
       "backups": 10,
       "pattern": "%d{dd/MM hh:mm} %-5p %m"

        "category": "logger"
        }
      ],
            "replaceConsole": true
      }

输出我的代码

[2017-05-24 15:57:00.924] [INFO] logger - tetsting

但是上面的输出不是我预期的。

此处的预期输出

[23-May-17 12:05:37] [INFO] logger - tetsting

请提前致谢。

1 个答案:

答案 0 :(得分:1)

这是一个诽谤:

const date = new Date('2017-05-23 12:05:37.327').toString('dd-MMM-yy hh:mm:ss')

编辑:对不起,这是一个log4js解决方案:

var log4js = require('log4js');
var monthNames = [
  "January", "February", "March",
  "April", "May", "June", "July",
  "August", "September", "October",
  "November", "December"
];

log4js.configure({
  appenders: [{
    type: "console",
    layout: {
      type: "pattern",
      pattern: "%x{ln} %-5p %m",
      tokens: {
        ln: function (data) {
          const date = new Date();
          var day = date.getDate();
          var monthIndex = date.getMonth();
          var year = date.getFullYear();
          var hours = date.getHours();
          var minutes = date.getMinutes();
          var seconds = date.getSeconds();
          return day + '-' + monthNames[monthIndex] + '-' + year + ' ' + hours + ':' + minutes + ':'
            + seconds;
        }
      }
    }
  }],
});

var logger = log4js.getLogger('cheese');
logger.debug('test');

输出:29-May-2017 14:39:4 DEBUG test

编辑2: conf.json:

{
  "appenders": [
    {
      "type": "console",
      "layout": {
        "type": "pattern",
        "pattern": "%x{ln} %-5p %m",
        "tokens": {}
      }
    }
  ]
}

logger.js:

var log4js = require('log4js');
var config = require('./conf.json')
var monthNames = [
  "January", "February", "March",
  "April", "May", "June", "July",
  "August", "September", "October",
  "November", "December"
];
config.appenders[0].layout.tokens.ln = function () {
  const date = new Date();
  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  return day + '-' + monthNames[monthIndex] + '-' + year + ' ' + hours + ':' + minutes + ':'
    + seconds;
};
log4js.configure(config);

var logger = log4js.getLogger('cheese');
logger.debug('test');