Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js - Adding timestamp to error logs

This should be simple, but I can't find a way to prepend a timestamp to node.js error logs. I'm not talking about the output of console.*, but rather the errors that are emitted by exceptions.

I'm running my app with forever, which outputs errors to a separate log and I have no way of determining when the errors occur - which is why I want to add a timestamp.

Can someone point me in the right direction?

like image 228
karnage Avatar asked Dec 10 '13 22:12

karnage


1 Answers

Are you talking about unhandled exceptions?

Do

process.on('uncaughtException', function (e) {
  console.log(new Date().toString(), e.stack || e);
  process.exit(1);
});

Of course you'll have a nicer time parsing the date with something like momentjs

For exceptions you handle yourself, use a logging library such as winston, which allows you among many other things, to pick a format.

Update

See what the node docs have to say

Do not use it as the node.js equivalent of On Error Resume Next. An unhandled exception means your application - and by extension node.js itself - is in an undefined state. Blindly resuming means anything could happen.

like image 70
bevacqua Avatar answered Oct 29 '22 06:10

bevacqua