Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

small optimization for use with winston #2

Open
enunez opened this issue Oct 23, 2021 · 1 comment
Open

small optimization for use with winston #2

enunez opened this issue Oct 23, 2021 · 1 comment

Comments

@enunez
Copy link

enunez commented Oct 23, 2021

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'));
@clamb-respondent
Copy link

winstonjs/winston#1338 Has a good discussion on this ^^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants