您好我的制作团队有要求,我需要每小时创建一次日志,我知道每天都有winston支持,但这对我没有帮助。 有可能这样做吗?
答案 0 :(得分:9)
您可以每小时旋转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-17T16
,log_file_name.log.2013-12-17T17
等。
我希望这会有所帮助。
答案 1 :(得分:0)
已更新 正如@Tom所提到的,旋转日志已从winston移出,并在需要时加载
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);
}
所附图片中提到的结果文件
附加:我创建了具有不同用例的winston示例,可能会有所帮助 https://github.com/shivashanmugam/node-lab/blob/master/winston/index.js