如何针对Node.js中发生的每个错误发送电子邮件?

假设我的node.js应用程序正在运行。 如果出现错误(我的意思是所有的错误,不仅仅是networking错误,如果发生错误,它会计数),我怎样才能调用一个函数发送邮件给我?

基本上,在我想把它写到err.out之前,我想要一封邮件发给我。

我使用node.js和expression。

编辑:我知道如何发送电子邮件。 我想知道的问题是如何截取错误 。 你知道如何发生错误,它会logging到out.log ? 那么,现在,我是tail -f out.log,监视错误。 我不能整天坐在家里这样做。 我想要通过电子邮件发送给我的错误,只要在out.log中popup。

我想要通过电子邮件发送给我的所有错误。 (不只是expression错误)。 如果它被logging,我想通过电子邮件发送错误。

您可以用发送电子邮件的一个实现replace节点全局console.error()函数:

console.error = function(msg) { // send email // ... // additionaly log process.stderr.write(msg); }; 

然后每个库中对console.error()的每个调用都会调用你的具体实现发送邮件;)

寻找nodejs smtp客户端/服务器

emailjs例子

 var email = require("./path/to/emailjs/email"); var server = email.server.connect({ user: "username", password:"password", host: "smtp.gmail.com", ssl: true }); // send the message and get a callback with an error or details of the message that was sent server.send({ text: "i hope this works", from: "you <username@gmail.com>", to: "someone <someone@gmail.com>, another <another@gmail.com>", cc: "else <else@gmail.com>", subject: "testing emailjs" }, function(err, message) { console.log(err || message); }); 

由于所有日志条目都存储在有限数量的日志文件中,而不是试图拦截所有可能的错误事件,为什么不build立文件更改监视器并将新行邮寄给您? 这样,您也可以安排最后一小时/天/ …的汇总日志条目的时间间隔,与打开单独的邮件相比,这将更容易完成。