Winston: add a simple example to log a json value , on the guide

Created on 6 Dec 2017  路  5Comments  路  Source: winstonjs/winston

I've just read all the documentation for winston, but I have not found how to print a simple object or json value with log.

I've tried:

logger.log('info', 'values', values);

and I get only, in this case my 'values' variable is a plain object with properties and values:

{"level":"info","message":"values"}

using:

const winston = require('winston');

const logger = winston.createLogger({
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'resolver.log' })
]
});

installed with:

npm i winston@next --save

faq

Most helpful comment

Here's the simplest example I could put together.

https://gist.github.com/a-h/d02bd4ff238e5923fcf5369233e51401

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')

All 5 comments

Here's the simplest example I could put together.

https://gist.github.com/a-h/d02bd4ff238e5923fcf5369233e51401

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')

thanks it's working , just need to add support for simple values:

logger.info('my value', 4);

I mean sometimes i need just to print a value that is not object or json. Must I use format conditional accort to type of value ?

thanks

If you're set on that form of logging how about just using string interpolation?

logger.info(`my value: ${4}`);

I'd be more inclined to do this:

logger.info('', { "simple_value": 4 });

Or add a bit of information to the state of the program at the point in time:

logger.info('database operation returned', { "simple_value": 4 });

nice idea ! thanks

Seems like this issue is resolved. Thanks @a-h

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mohanen picture mohanen  路  4Comments

kjin picture kjin  路  3Comments

anks333 picture anks333  路  3Comments

ghost picture ghost  路  4Comments

alditis picture alditis  路  3Comments