Last active
May 17, 2022 05:27
-
-
Save a-h/d02bd4ff238e5923fcf5369233e51401 to your computer and use it in GitHub Desktop.
JSON logging in winston with a timestamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const winston = require('winston'); | |
const MESSAGE = Symbol.for('message'); | |
const jsonFormatter = (logEntry) => { | |
const base = { timestamp: new Date() }; | |
const json = Object.assign(base, logEntry) | |
logEntry[MESSAGE] = JSON.stringify(json); | |
return logEntry; | |
} | |
const logger = winston.createLogger({ | |
level: 'info', | |
format: winston.format(jsonFormatter)(), | |
transports: new winston.transports.Console(), | |
}); | |
logger.info('message content', { "context": "index.js", "metric": 1 }) | |
logger.info('message content 2') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# npm install | |
# node index.js | |
{"timestamp":"2017-12-07T16:07:10.518Z","context":"index.js","metric":1,"level":"info","message":"message content"} | |
{"timestamp":"2017-12-07T16:07:10.520Z","message":"message content 2","level":"info"} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "winston_test", | |
"main": "index.js", | |
"dependencies": { | |
"winston": "^3.0.0-rc1" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
Thanks but in latest RC - this prints out an 'undefined', so does the scream example in the docs - any idea why?