简体   繁体   English

node.js 异步日志记录和未处理的服务器异常的最佳实践

[英]Best practice for node.js asynchronous logging and unhandled server exceptions

We recently changed our logging code in node.js/Express.js to write to the console asynchronously.我们最近更改了 node.js/Express.js 中的日志记录代码,以异步写入控制台。 However, this comes with an issue where if after the asynchronous code is initiated (and when it runs it will emit a log message), the synchronous code run after that initiation crashes the server, then the logs are never written.但是,这会带来一个问题,如果在异步代码启动之后(并且当它运行时它会发出一条日志消息),在该启动之后运行的同步代码会使服务器崩溃,那么日志就永远不会被写入。

Is there an established pattern or best practice for handling this so that disk I/O is not a blocker for logging, but in the event of an unhandled exception (such as an exception occurring in our last-chance exception handler in Express.js), the logs will still be written to disk/console?是否存在处理此问题的既定模式或最佳实践,以便磁盘 I/O 不会成为日志记录的障碍,而是在发生未处理的异常时(例如 Express.js 中的最后机会异常处理程序中发生的异常) ,日志仍将写入磁盘/控制台吗?

I thought about starting a separate logging process and doing inter-process communication, but that feels pretty darn heavy just to avoid a little bit of I/O.我考虑过启动一个单独的日志记录进程并进行进程间通信,但为了避免一点 I/O,这感觉相当沉重。 And I don't think a separate thread will work—won't the node.js unhandled exception that takes the server down also kill all threads started/owned by the process?而且我不认为一个单独的线程会起作用——node.js 未处理的异常会导致服务器关闭也杀死进程启动/拥有的所有线程吗? (I'm no expert in this area.) (我不是这方面的专家。)

Or is it better to just write to the console synchronously in our logger, and thereby prevent this situation in the first place?还是在我们的记录器中同步写入控制台更好,从而首先防止这种情况?

Your changed logging code should give you access to the underlying stream.您更改后的日志记录代码应该可以让您访问底层 stream。 The synchronous code that crashes the server likely does it by throwing an uncaught exception.导致服务器崩溃的同步代码很可能通过抛出未捕获的异常来实现。 Which you can catch using您可以使用它来捕捉

process.on('uncaughtException', err => { logSync(err); exit(errCode); })

Then log the exception synchronously using the stream or console and exit.然后使用 stream 或控制台同步记录异常并退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM