I am using winston-js
as a logger in my project - it works fine, however I'm now trying to add a unique log Id to each log line for debugging.
I have 2 transports - 1) Console, 2) File.
I'd like the log ID for the same log line to be the same in for both transports. At the moment, as the request goes through my system, the log ID stays the same.
In the example code below I'm using winston's defaultMeta
- which doesn't seem to work, however i've tried adding functions too - and get the same result.
I do I set the log ID for the same log line to be the same in for both transports?
Note: I am using UUID for the LogId in my project - for simplicity I've used a single number in the examples.
So for example my current setup does:
File
logID: 1 | Request: Post | Request: 1
logID: 1 | Request: Post | Request: 1
logID: 2 | Request: Post | Request: 2
Console
logID: 1 | Request: Post | Request: 1
logID: 1 | Request: Post | Request: 1
logID: 2 | Request: Post | Request: 2
I'd like:
File
logID: 1 | Request: Post | Request: 1
logID: 2 | Request: Post | Request: 1
logID: 3 | Request: Post | Request: 2
Console
logID: 1 | Request: Post | Request: 1
logID: 2 | Request: Post | Request: 1
logID: 3 | Request: Post | Request: 2
.
function devLogger () {
const logFormat = printf(({ level, message, timestamp, stack, ...meta }) => {
var logId = meta.logId
return `${timestamp} [${level}] ${message} | ${logId} | Console`;
})
const jsonFormat = printf(({ level, message, timestamp, stack, ...meta }) => {
var logId = meta.logId
return `${timestamp} [${level}] ${message} | ${logId} | File`;
})
return createLogger({
defaultMeta: { logId: uuidv4() }, // Add logId to both transports
transports: [
new transports.Console({
level: 'debug',
format: combine(
format.colorize(),
timestamp({ format: 'DD-MM-YY HH:mm:ss' }),
logFormat
),
}),
new transports.File({
level: 'debug',
filename: 'error.log',
format: combine(timestamp({ format: 'DD-MM-YY HH:mm:ss' }), errors({ stack: true }), jsonFormat),
}),
]
});
}