user13824605
user13824605

Reputation:

Winston is only logging .info errors and doesn't log error to file or mongodb

I am using express-mongoose for my backend and winston as my logger. The problem is that winston is only logging the info messages not errors The logs in server.log enter image description here

Error messages only get logged on console but neither in the file nor mongodb enter image description here

the logger code

const { createLogger, format, transports } = require('winston');

// Import mongodb
require('winston-mongodb');

module.exports = createLogger({

transports:[
//Console transport
    new transports.Console(),

// File transport
    new transports.File({
    filename: 'logs/server.log',
    format:format.combine(
        format.timestamp({format: 'MMM-DD-YYYY HH:mm:ss'}),
        format.align(),
        format.printf(info => `${info.level}: ${[info.timestamp]}: ${info.message}`),
    )}),

// MongoDB transport
    new transports.MongoDB({
        level: 'error',
        //mongo database connection link
        db : 'mongodb://localhost/logs',
        options: {
            useUnifiedTopology: true
        },
        // A collection to save json formatted logs
        collection: 'edushare_logs',
        format: format.combine(
        format.timestamp(),
        // Convert logs to a json format
        format.json())
    })]
});

I created an error by not defining the jwt. the code

const logger = require("./utils/logger")
if (!config.get("jwtPrivateKey")){
    logger.error("FATAL ERROR!! JWT is not defined!")
    process.exit(1)
}

Upvotes: 1

Views: 754

Answers (1)

The winston "console transport" is synchronous, however the processes to write to mongo or file are asynchronous. In this case you can use the winston function callback. Try this:

const logger = require("./utils/logger")
if (!config.get("jwtPrivateKey")) {
    logger.error("FATAL ERROR!! JWT is not defined!", () => {
        exit(1);
    });
}

Upvotes: 1

Related Questions