7

嗨,我的生产团队有一个要求,我需要每小时创建一次日志,我知道 winston 每天都支持,但这对我没有帮助。有可能做到这一点吗?

4

2 回答 2

10

您可以每小时轮换 Winston 日志。您需要HH在日期模式中提供小时 ( )。

请检查下面的示例代码:

var winston     = require ('winston');
var path        = require ('path');

var transports  = [];

transports.push(new winston.transports.DailyRotateFile({
  name: 'file',
  datePattern: '.yyyy-MM-ddTHH',
  filename: path.join("some_path", "log_file_name.log")
}));

var logger = new winston.Logger({transports: transports});

// ... and logging
logger.info("some info log ...", {extraData: 'abc'});

文件名如下:log_file_name.log.2013-12-17T16log_file_name.log.2013-12-17T17

我希望这会有所帮助。

于 2013-12-18T23:14:13.950 回答
2

已更新正如@Tom 提到的旋转日志已移出温斯顿并在需要时加载

npm install winston-daily-rotate-file

代码示例

const winston = require('winston')
require('winston-daily-rotate-file');
const path = require('path');
let transports  = [];
const { createLogger } = winston;
transports.push(
    new winston.transports.DailyRotateFile({
      name: 'file',
      datePattern: 'YYYY-MM-DD-THH-mm',
      filename: path.join(__dirname, 'rotate_logs', 'log_file.log')
    })
)
var logger = createLogger({ transports: transports })

如果想测试上面的代码,完整的例子

dataLog(0)
function dataLog(secondsPassed){
    setTimeout(function(){
        let dateNow = new Date();
        logger.info(`seconds passed ${secondsPassed} and Time is ${dateNow}`);
        console.log(`${secondsPassed}`);
        if(dataLog != 130){ //when reaches 130 seconds stops logging
              dataLog(++secondsPassed);
        }
    },1000);
}

附图中提到的结果文件

轮换日志的结果

额外:我创建了具有不同用例的温斯顿示例,可能会有所帮助 https://github.com/shivashanmugam/node-lab/blob/master/winston/index.js

于 2018-10-03T04:22:55.683 回答