微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Winston:如何等待 winston 将所有日志写入特定传输例如 FileTransport

如何解决Winston:如何等待 winston 将所有日志写入特定传输例如 FileTransport

我正在使用 winston登录我的基于 Express 的网络应用程序。我想要的是在 api 控制器中动态添加传输以拦截特定请求的所有日志事件并将累积的日志返回给客户端。

不幸的是,实现起来并不容易,因为有时 winston 日志记录是异步的。不总是,但有时。因此,在我删除添加的传输的情况下,并非所有事件都被记录下来。

router.post('/engine/:id/start',async (req: express.Request,res: express.Response,next) => {
  const logger = req.log; // this is a winston logger for this particular request 

  const logFilename = path.join(getTempDir(),'log_run_' + getCurrentDateTimestamp());
  let fileTransport = new winston.transports.File({
    tailable: true,filename: logFilename,format: winston.format.printf(
        (info) => `${info.timestamp} ${info.level}: ${info.message}`,),close: () => {
      // this one is called but at the moment of execution not all events are written (looks like a bug to me)
    }
  });
  fileTransport.on('finish',() => {
    // not ever called 
  });
  fileTransport.on('close',() => {
    // not ever called
  });
  logger.add(fileTransport);
  
  // execute main operation
  let contoller = new Controller(logger);
  await controller.run();

  // here's a problem - at the moment of removal of transport,there Could be some events pending to be written,and so the log written from the file won't contain all log events.
  logger.remove(fileTransport!);
  const log = fs.readFileSync(logFilename,'utf8');
  // send log via email
  notifyOnSuccess(log);
});

在这里看到了很多关于如何在退出进程之前等待 FileTransport 刷新的类似主题的问题,但这是完全不同的用例,因为我不需要在这里停止记录。我只需要确保所有事件都被刷新。

我可以想出一个解决方法 - 而不是使用 FileTransport 使用某种自定义流传输来观察所有事件并在特定事件上在传输移除之前向该位置发出信号(将标志翻转为真)。但我想使用标准的 FileTransport。

有没有办法等待 winston 刷新事件队列或特定传输在删除它之前写入所有内容

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。