我正在使用 winston
进行日志记录,并且大多数情况下它运行良好,但是当出现异常时,它只是不打印任何详细信息。
这是我配置 winston
的代码:
// Create logger
const logger = winston.createLogger()
// Create timestamp format
const tsFormat = () => (new Date()).toLocaleTimeString()
// Attach transports based on app mode
if (process.env.APP_MODE === 'production') {
// Log to file
logger.add(new (winston.transports.DailyRotateFile)({
filename: path.join(__dirname, '../logs/errors-%DATE%.log'),
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
format: winston.format.json(),
handleExceptions: true
}))
} else {
// Log to the console
logger.add(new (winston.transports.Console)({
timestamp: tsFormat,
colorize: true,
handleExceptions: true
}))
}
module.exports = logger
我也在使用 Express
并且在我的错误处理中间件中,我有这个代码:
const logger = require('../config/winston')
function (err, req, res, next) {
console.log(err)
logger.error(err)
res.status(500).send({ error: 'Please try again later.' })
}
问题是当发生错误时,所有winston
日志都是:
{"level":"error"}
虽然旧的 console.log()
显示:
TypeError: Cannot read property 'filename' of undefined
at router.post (/Users/balazsvincze/Desktop/testapi/app/routes/upload.js:16:33)
at Layer.handle [as handle_request] (/Users/de/Desktop/testapi/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/balazsvincze/Desktop/testapi/node_modules/express/lib/router/route.js:137:13)
at Immediate.<anonymous> (/Users/balazsvincze/Desktop/testapi/node_modules/multer/lib/make-middleware.js:53:37)
at runCallback (timers.js:814:20)
at tryOnImmediate (timers.js:768:5)
at processImmediate [as _immediateCallback] (timers.js:745:5)
如何让 winston
记录类似的内容,包括堆栈跟踪?
非常感谢!
编辑:如果我将 logger.error(err) 行更改为 logger.error(err.message),至少我得到这个:
{"message":"Cannot read property 'filename' of undefined","level":"error"}
离我所追求的还很远。
最佳答案
我认为你缺少的是 format.errors({ stack: true })
在 winston.createLogger
.
const logger = winston.createLogger({
level: 'debug',
format: format.combine(
format.errors({ stack: true }),
print,
),
transports: [new transports.Console()],
});
见 this GitHub thread了解更多信息。
发生这种情况的原因是因为有趣的 Error
对象属性,如 .stack
, 是不可枚举的。某些函数会检查其参数是否为 Error
实例,例如 console.error
, 和其他函数忽略所有不可枚举的属性,如 winston.<log-level>
和 JSON.stringify
.
> console.error(new Error('foo'))
Error: foo
at repl:1:15
at Script.runInThisContext (vm.js:124:20)
...(abbr)
> JSON.stringify(new Error('foo'))
'{}'
话虽如此,让错误记录器基本上忽略错误是非常糟糕的可用性......我只是为此浪费了太多时间。
关于node.js - Winston 不显示错误详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51630896/