0

I have set winston logger on the first time

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

const logLevels = { error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 };

const logger = createLogger({

    level: logLevels[process.env.LOG_LEVEL] !== undefined ? process.env.LOG_LEVEL : 'info',
    format: format.combine(
        format.colorize(),
        format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss'
        }),
        format.simple(),
        format.printf(context => {
            const msgstr = JSON.stringify(context.message, null, null)
            console.log(context);
            return `[${context.level}] [${context.timestamp}] ${msgstr}`;
        }),
    ),
    transports: [new transports.Console()]
});

export default logger

Not sure if it is the right wat to do it, but when I log errors I don't see the path inside the context object.

I catch the errors in the end of the app

app.use((err, req, res, next) => {
    logger.error(err)
    if (res.headersSent) {
        return next(err)
    }
    res.status(500).send({ error: err })
});

Any help would be great, thanks!

Smiled_One
  • 445
  • 1
  • 4
  • 17

1 Answers1

1

You should add the stack trace within your call to the error logger:

app.use((err, req, res, next) => {
    logger.error(
        '%s\n%s',
        err.toString().replace(/^Error/, err.constructor.name),
        err.stack
            ?.split('\n')
            .slice(1, 6)
            .join('\n')
    );
    if (res.headersSent) {
        return next(err)
    }
    res.status(500).send({ error: err })
});

I added the concrete error class with the first 6 lines of stack trace below. As I use the %s syntax you need the splat setting so maybe use a logger like:

const logger = createLogger({
    // To see more detailed errors, change this to 'debug'
    level: config('log.level'),
    format: format.combine(
        format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        format.splat(),
        format.printf(
            info =>
                `${info.timestamp} ${info.level.toLocaleUpperCase().padEnd(8)} ${info.message}` +
                (info.splat !== undefined ? `${info.splat}` : ' ')
        ),
        format.colorize({ all: true })
    ),
    transports: [
        new transports.Console()
    ]
})
Alinex
  • 914
  • 8
  • 18