为什么 Winston 不将错误记录到文件中?

Why does Winston not log errors to file?

我是 Winston 的新手,当代码出现错误时,它会记录到控制台而不是日志文件。信息正确记录到另一个文件,但错误没有。

这是我的 logger.js 文件:

const winston = require('winston')

let logger

module.exports.init = () => {
  logger = winston.createLogger({
    level: 'info',
    format:  winston.format.simple(),
    transports: [
      new winston.transports.Console(),
      new winston.transports.File({ filename: './logs/error.log', level: 'error' }),
      new winston.transports.File({ filename: './logs/info.log' })
    ]
  })

  process.on('uncaughtException', ex => {
    logger.error(ex.message)
    process.exit(1)
  })

  process.on('unhandledRejection', ex => {
    logger.error(ex.message)
    process.exit(1)
  })
}

module.exports.use = () => logger

我已经使用了代码 ,但它不起作用。非常感谢任何帮助。

我怀疑您的进程在有机会写入日志之前就已经退出了。我建议等到所有消息都被记录后再退出,请参阅 Awaiting logs to be written in winston

process.on('uncaughtException', ex => {
  logger.error(ex.message)
  logger.on('finish', () => {
      process.exit(1);
  });
})

process.on('unhandledRejection', reason => {
  logger.error("unhandledRejection: " + reason)
  logger.on('finish', () => {
      process.exit(1);
  });
})