Skip to content

small optimization for use with winston #2

@enunez

Description

@enunez

Thanks for this solution. It's unbelievable that the winston developers still haven't fixed this issue after so many years. Anyway, since this problem only seems to happen with Error objects, it's better to only apply your toJSON() transformation for messages that are actually Error objects. Here's a little function that does that -- it wraps logger.log() and all the other methods, too.

import winston from 'winston';
import clone from 'utils-deep-clone';

function fixErrorHandling(logger) {
  ['log', 'error', 'warn', 'info', 'http', 'verbose', 'debug', 'silly'].forEach(
    (method) => {
      const [orig, pos] = [Symbol(), method === 'log' ? 1 : 0];
      logger[orig] = logger[method];
      logger[method] = (...args) => {
        if (args[pos] instanceof Error) {
          args[pos] = clone.toJSON(args[pos]);
        }
        return logger[orig](...args);
      };
    }
  );
}

const log = winston.createLogger({
  format: winston.format.simple(),
  transports: [new winston.transports.Console()],
});

fixErrorHandling(log);

log.error(new Error('uh oh'));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions