Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top