如何记录“catched”异常?

时间:2013-05-07 23:38:35

标签: javascript node.js winston

winston处理未捕获的异常时,它会输出未捕获异常的详细信息。如何对“捕获的异常”执行相同的操作?

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

我检查了源代码,似乎有logException method,但我不知道如何使用它。

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'

4 个答案:

答案 0 :(得分:1)

您可以将捕获的异常发回到进程,错误将由winston.Logger捕获。例如:

process.emit('uncaughtException', err);

答案 1 :(得分:1)

var winston = require('winston');
var err = new Error('test error.');
winston.error(winston.exception.getAllInfo(err));

答案 2 :(得分:0)

logExceptionTransport的方法,而不是Logger类的方法。您需要的是error方法:

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

答案 3 :(得分:0)

使用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)

或使用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;