简体   繁体   English

node.js - PM2将未捕获的异常记录到第三方服务(作为Logentries)

[英]node.js - PM2 log uncaught exceptions to third-party service (as Logentries)

I'm using pm2 ( https://github.com/Unitech/pm2 ) in my node.js project. 我在我的node.js项目中使用pm2( https://github.com/Unitech/pm2 )。 Also I'm sending logs of errors of the app in Logentries ( https://logentries.com ). 此外,我在Logentries( https://logentries.com )发送应用程序错误日志。

I wonder is it possible to log uncaught exceptions from the app (when something fails badly and pm2 restarts the app for example)? 我想知道是否可以从应用程序中记录未捕获的异常(例如,当某些内容失败并且pm2重新启动应用程序时)? I know that using process.on('uncaughtException') is bad practice so would like to hear some suggestions. 我知道使用process.on('uncaughtException')是不好的做法,所以希望听到一些建议。

Thanks! 谢谢!

Where did you read that process.on('uncaughtException') is a bad practice? 你在哪里读过那个process.on('uncaughtException')是一个不好的做法?

As long as you exit the process after logging the exception I don't see what's bad, here is an example: 只要在记录异常后退出进程,我就看不出有什么不好,这是一个例子:

process.on('uncaughtException', function(e) {
    console.error('Ouch, an unhandled exception');
    //I like using new Error() for my errors (1)
    console.error(e instanceof Error ? e.message : e);
    process.exit(1);
});

(1): Javascript Error reference (1): Javascript错误参考

Edit pm2-interface is now deprecated, use require('pm2') instead. 编辑 pm2-interface现已弃用,请改用use require('pm2') You will be able to do exactly the same as below by using bus system events . 通过使用总线系统事件,您将能够完成与下面完全相同的操作。


An alternative with pm2 is to use pm2-interface and listening to the process:exit or process:exception events: 使用pm2的替代方法是使用pm2接口并监听process:exitprocess:exception事件:

var ipm2 = require('pm2-interface')();

ipm2.on('ready', function() {
  console.log('Connected to pm2');

  ipm2.bus.on('process:exception', function(data){
    console.log(data.pm2_env.name + 'had an exception');
  });
});

This is really usefull when managing more than one process through a monitoring process. 当通过监视过程管理多个进程时,这非常有用。

You might want to check the blog post on how to build a custom pm2 logger . 您可能想查看有关如何构建自定义pm2记录器的博客文章。 It can give you some ideas about monitoring processes through pm2-interface . 它可以通过pm2-interface为您提供有关监控过程的一些想法。

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

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