Home > Back-end >  Winston never writing to log file if script crashes
Winston never writing to log file if script crashes

Time:11-10

I have a project that I need log files for, which is why I want to use winston. But over its runtime it may crash at some point, so I was doing some testing:

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');

This basically just prints hello world 100000 times and than errors out. The problem I have is that combined.log is only written to if the program doesn't crash (presumably at the very end). So why is winston only writing to the actual log once its done running. And how can I make it write to the file even if there may be an exception?

EDIT:

interestingly, it works if you add a 1 second delay between the error

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()

CodePudding user response:

Use 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');

Although, really, you should always catch any exceptions etc

  • Related