Reputation: 460
Using Winston logger with my NodeJS project I cant find a way to configure logger to output logs in following format:
[ 'timestamp' ] : [ 'level' ] -> 'message' [ if error: trace else nothing ]
My current format looks following:
const logger = winston.createLogger({
transports: new transports.Console({
format: format.combine(
format.errors({ stack: true }),
format.timestamp({ format: "MMM-DD-YYYY HH:mm:ss" }),
format.align(),
format.printf(
({ level, message, timestamp, stack }) =>
`[${timestamp}] [${level}]: ${message} ${level == "error" ? stack : ""}`
)
),
}),
});
logging for example: logger.error("Some text on error");
results in: [Jan-20-2022 14:20:43] [error]: Some text on error undefined
What is the problem?
Upvotes: 2
Views: 3746
Reputation: 136505
Getting stack-trace works only with Error
objects which have Error.stack
property:
logger.error(new Error("Some text on error"));
See documentation for logform.format.errors
:
The
errors
format allows you to pass in an instance of a JavaScriptError
directly to the logger. It allows you to specify whether not to include the stack-trace.
Here is a complete TypeScript/JavaScript example:
#!/bin/env ts-node-esm
import winston from 'winston';
const log = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.errors({stack: true}),
winston.format.timestamp({format: "YYYY-MM-DD HH:mm:ss.SSS"}),
winston.format.printf(({timestamp, level, message, stack}) => {
const text = `${timestamp} ${level.toUpperCase()} ${message}`;
return stack ? text + '\n' + stack : text;
}),
),
transports: [
new winston.transports.Console(),
],
});
function fail() {
throw new Error("Some text on error")
}
try {
fail();
}
catch(e) {
console.log("console");
console.log("abc", e);
console.log();
console.log("winston");
log.error("abc", e);
console.log();
log.info("No error");
log.error("No error");
}
Output:
console
abc Error: Some text on error
at fail (file:///home/max/src/quant-research/tests/ts-test.ts:20:11)
at file:///home/max/src/quant-research/tests/ts-test.ts:24:5
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:533:24)
at async loadESM (node:internal/process/esm_loader:91:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
winston
2023-02-22 02:37:00.063 ERROR abc Some text on error
Error: Some text on error
at fail (file:///home/max/src/quant-research/tests/ts-test.ts:20:11)
at file:///home/max/src/quant-research/tests/ts-test.ts:24:5
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:533:24)
at async loadESM (node:internal/process/esm_loader:91:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
2023-02-22 02:37:00.063 INFO No error
2023-02-22 02:37:00.064 ERROR No error
Upvotes: 4