12

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

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

我检查了来源,似乎有一种logException方法,但我不知道如何使用它。

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

4 回答 4

1

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

process.emit('uncaughtException', err);
于 2014-02-25T10:15:07.087 回答
1
var winston = require('winston');
var err = new Error('test error.');
winston.error(winston.exception.getAllInfo(err));
于 2016-04-07T12:33:26.437 回答
0

logException是 的方法Transport,而不是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

于 2013-10-29T04:41:07.027 回答
0

使用日志格式

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;
于 2020-08-20T19:08:23.130 回答