Sandra Schlichting
Sandra Schlichting

Reputation: 26026

Possible to have Winston to include which logger that created the entry?

The below PoC outputs

{"clock":"aaaa","id":"bbb","state":"ccc","level":"info","message":"Down","timestamp":"2021-02-04 15:25:25"}

but it doesn't include which logger that wrote the entry. Ie. in this case it was monitorLogger.info(). The info part is represented in the level tag, but the entry doesn't mention monitorLogger.

Question

Is it possible to get winston to include a tag of which logger that created the entry?

check.js

const {monitorLogger} = require('./logger');

monitorLogger.info('Down', {
  clock: 'aaaa',
  id: 'bbb',
  state: 'ccc'
});

logger.js

const { createLogger, format, transports, config } = require('winston');

const monitor = createLogger({
  transports: [
    new transports.Console()
  ],
  format: format.combine(
    format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    format.json(),
  ),
  exceptionHandlers: [
    new transports.Console()
  ]
});

module.exports = {
 monitorLogger: monitor
};

Upvotes: 0

Views: 66

Answers (2)

Raj
Raj

Reputation: 274

Under the createlogger, can we add a label like below

const { createLogger, format, transports, config } = require('winston');

const { combine, timestamp, label, json } = format; // <---- additional import

const monitor = createLogger({
  transports: [
    new transports.Console()
  ],
  format: format.combine(
    format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    format.json(),
    label({ label: 'monitor' })
  ),
  exceptionHandlers: [
    new transports.Console()
  ]
});

module.exports = {
 monitorLogger: monitor
};

Sample output would be

{"clock":"aaaa","id":"bbb","state":"ccc","level":"info","message":"Down","label":"monitor","timestamp":"2021-02-04 15:25:25"}

Upvotes: 1

d2xdt2
d2xdt2

Reputation: 371

const { createLogger, format, transports, config } = require('winston');
const { combine, timestamp, label, json } = format;

const monitor = createLogger({
  transports: [
    new transports.Console()
  ],
  format: combine(
    format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    label({ label: 'monitor' }),
    timestamp(),
    json(),
  ),
  exceptionHandlers: [
    new transports.Console()
  ]
});

module.exports = {
 monitorLogger: monitor
};

gives

{"clock":"aaaa","id":"bbb","state":"ccc","level":"info","message":"Down","timestamp":"2021-02-04 21:32:54","label":"monitor"}

Upvotes: 0

Related Questions