12

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?

1
  • Have you considered proxying your logging out to a shell script that can retrieve the timestamp? Commented Dec 10, 2013 at 22:04

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! That was what I was looking for. I had already overloaded the console.* methods to use a timestamp, so simply console.log-ing the error worked for me. I'm curious how the errors are output by default, since they must not use console.log.
Would it be bad to omit the process.exit(1) line?
Also of interest is new Date().toLocaleString(); which returns a format like "12/7/2016, 11:22:22 PM"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.