puzpuzpuz / cls-rtracer

Request Tracer - CLS-based request id generation for Express, Fastify, Koa and Hapi, batteries included
MIT License
311 stars 24 forks source link

Integration with winston JSON #38

Closed aniketkalamkar closed 4 years ago

aniketkalamkar commented 4 years ago

I am not able to read the rtracer.id() in the winston logger config file and set the value as separate attribute in the json log. Can someone please help if the similar is implemented with sample piece of code. Thanks

puzpuzpuz commented 4 years ago

@aniketkalamkar could you provide sample code for what you're trying to achieve? I'm not sure if I understand the question.

puzpuzpuz commented 4 years ago

Closing due to inactivity. Please comment if you have an update here.

pyrho commented 4 years ago

I think the best way to achieve what OP wants is to create a dynamic getter in the log metadata (as explained here):

import * as rTracer from 'cls-rtracer';
import winston, { format } from 'winston';
const { combine, timestamp } = format;

export const Logger = (() => {
    const logger: winston.Logger = winston.createLogger({
        level: 'silly',
        format: combine(timestamp(), winston.format.json()),
        defaultMeta: {
            get requestId() { // This will run each time a log function is called
                return rTracer.id();
            },
        },
        transports: [new winston.transports.Console()],
    });
    return logger;
})();

example log output:

{
   "message":"a message",
   "level":"debug",
   "requestId":"92706940-070a-11eb-87e1-09ce93f1c9e4",
   "timestamp":"2020-10-05T12:59:15.302Z"
}
puzpuzpuz commented 4 years ago

Thanks for the update @pyrho!