【问题标题】:Winston never writing to log file if script crashes如果脚本崩溃,温斯顿永远不会写入日志文件
【发布时间】:2022-11-10 18:14:01
【问题描述】:

我有一个需要日志文件的项目,这就是我想使用winston 的原因。但是在它的运行时它可能会在某个时候崩溃,所以我做了一些测试:

const winston = require('winston');

const logger = winston.createLogger({
    transports: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: 'combined.log' })
    ]
});

let i=100000;
while(i-->0){
    logger.info('Hello world');
}

throw new Error('Error');

这基本上只是打印 hello world 100000 次而不是错误。我遇到的问题是,combined.log 仅在程序没有崩溃时才被写入(大概在最后)。那么为什么winston 只在运行完成后才写入实际日志。即使可能有异常,我怎样才能让它写入文件?

编辑:

有趣的是,如果您在错误之间添加 1 秒的延迟,它会起作用

const winston = require('winston');
const fsp = require('fs').promises;

let a=async ()=>{

    try{
        await fsp.unlink('combined.log');
    }catch(e){

    }

const logger = winston.createLogger({
    transports: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: 'combined.log' })
    ]
});

    let i=100000;
    while(i-->0){
        logger.info('Hello world');
    }

    //wait 1 seconds
    await new Promise((resolve)=>setTimeout(resolve,1000));
//  await new Promise((resolve,reject)=>{resolve()});

    throw new Error('Error');
}

a()

【问题讨论】:

标签: node.js winston


【解决方案1】:

使用handleExceptions: true

const winston = require('winston');

const logger = winston.createLogger({
    transports: [
        new winston.transports.Console({handleExceptions: true}),
        new winston.transports.File({ filename: 'combined.log',handleExceptions: true})
    ]
});

let i=100000;
while(i-->0){
    logger.info('Hello world');
}

throw new Error('Error');

虽然,真的,你应该总是捕捉任何异常等

【讨论】:

  • 谢谢。但是为什么我需要捕获异常才能让winston 写入日志文件呢?
猜你喜欢
  • 2023-03-11
  • 2018-11-19
  • 1970-01-01
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
相关资源
最近更新 更多