13

When winston handles uncaught exceptions it prints a nice info of the uncaught exception.How can I do the same on "catched exceptions"?

if (err) {
 // winston. log the catched exception
}

I checked the source and there seems to be a logException method but I don't know how I could use it.

var logger = new winston.Logger({
  transports: [new winston.transports.Console({handleExceptions: true})]
})
var err = new Error('test error.')
logger.logException(err.message) //no method 'logException'
Jürgen Paul
  • 14,299
  • 26
  • 93
  • 133

4 Answers4

3

Use logform:

const { format } = require('logform');
const { errors } = format;

const errorsFormat = errors({ stack: true })

const info = errorsFormat.transform(new Error('Oh no!'));

console.log(info);
// Error: Oh no!
//     at repl:1:13
//     at ContextifyScript.Script.runInThisContext (vm.js:50:33)
//     at REPLServer.defaultEval (repl.js:240:29)
//     at bound (domain.js:301:14)
//     at REPLServer.runBound [as eval] (domain.js:314:12)
//     at REPLServer.onLine (repl.js:468:10)
//     at emitOne (events.js:121:20)
//     at REPLServer.emit (events.js:211:7)
//     at REPLServer.Interface._onLine (readline.js:282:10)
//     at REPLServer.Interface._line (readline.js:631:8)

Or use winston.format.errors({ stack: true }):

import winston from 'winston';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.errors({ stack: true }),
    winston.format.json(),
    winston.format.prettyPrint(),
  ),
  defaultMeta: { service: 'user-service' },
  transports: [
    new winston.transports.File({
      filename: 'log/combined.log',
      options: { flags: 'w' },
    }),
  ],
});

export default logger;
Vladimir
  • 195
  • 3
  • 5
1

You can emit catched exception back to process, error will by catched by winston.Logger. Example:

process.emit('uncaughtException', err);
1
var winston = require('winston');
var err = new Error('test error.');
winston.error(winston.exception.getAllInfo(err));
joniba
  • 3,339
  • 4
  • 35
  • 49
  • 3
    Maybe this is from an old version of winston, but there is no such API. https://github.com/winstonjs/winston – Seth Mar 09 '17 at 12:30
  • https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md#user-content-exceptions--exception-handling => winston.exception has been removed. Use: const exception = winston.ExceptionHandler(); – TJR Jun 29 '23 at 18:39
0

logException is a method of Transport, not of the Logger class. What you need is a error method:

var winston = require('winston');
var logger = new winston.Logger({
  transports: [new winston.transports.Console({handleExceptions: true})]
})
var err = new Error('test error.');
logger.error(err.message);

https://github.com/flatiron/winston#using-logging-levels

deadrunk
  • 13,861
  • 4
  • 29
  • 29