How do I send an email for every error that occurs

2020-06-18 03:21发布

问题:

Let's say my node.js app is running. If there is an error (I mean ALL errors. Not just the web error. If it goes to Err out, it counts) , how can I call a function to send an email to me?

Basically, before I want it to write to err.out, I want an email sent to me.

I'm using node.js and express.

Edit: I know how to send an email. The question I want to know is how to intercept the error. You know how when there's an error, it logs to out.log? Well, right now, I'm tail -f out.log, monitoring for errors. I can't sit at home all day doing this. I want errors emailed to me anytime it pops up in out.log.

I want all errors emailed to me. (Not just Express errors). If it's logged, I want that error emailed.

回答1:

You could replace nodes global console.error() function with one implementation sending emails:

console.error = function(msg) {
  // send email
  // ...

  // additionaly log
  process.stderr.write(msg);
};

Then every call in every library made to console.error() would call your specific implementation send out mails ;)



回答2:

Look for nodejs smtp clients/servers

emailjs example

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); });


回答3:

Since all log entries are stored in a limited number of log files, in stead of trying to intercept all possible error events, why not just set up a file change monitor and have the new lines mailed to you? That way you can also schedule intervals with summary log entries of the last hour/day/... which will be a lot easier to go through, compared to opening separate mails.