How to do correlation Id with winston?

Viewed 3136

I'm using Winston in my nodejs application.

const winston = require('winston');
const logger = winston.createLogger({
    transports: [
        new winston.transports.Console()
    ]
});

logger.info('What rolls down stairs');

I want to add to the log correlation id, but I do not want to write every time

 logger.info('What rolls down stairs', correlationId);

I want to Winston to do that. and for every log I want to get the correlationId as result of the function so I can send the correlationId to the user (not just output it to the console).

 const correlationId = logger.info('blabla')

Is it possible to do that with Winston?

2 Answers

For creating correlationId and setup by default in Winston every log, you need to use defaultMeta.

var correlationId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
const winston = require('winston');
const logger = winston.createLogger({
defaultMeta: { correlationId },
    transports: [
        new winston.transports.Console()
    ]
});

logger.info('What rolls down stairs');
import { v4 as uuidv4 } from "uuid";

export async function withCorrelationId(message:string) {
    const id = uuidv4()

    logger.info({
        message,
        id,
    });

    return id
}
Related