Skip to content

Instantly share code, notes, and snippets.

@a-h
Last active May 17, 2022 05:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-h/d02bd4ff238e5923fcf5369233e51401 to your computer and use it in GitHub Desktop.
Save a-h/d02bd4ff238e5923fcf5369233e51401 to your computer and use it in GitHub Desktop.
JSON logging in winston with a timestamp
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')
# 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"}
{
"name": "winston_test",
"main": "index.js",
"dependencies": {
"winston": "^3.0.0-rc1"
}
}
@arliber
Copy link

arliber commented Apr 13, 2018

Hi,
Thanks but in latest RC - this prints out an 'undefined', so does the scream example in the docs - any idea why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment