0

I'm trying to get stdout and stderr to make it to my log file for a cron process. Currently, stdout makes it as intended, but stderr does not. My timestamps are creating the issue. If I remove the pipe ts part, both stdout and stderr to make it to the log file, but the lines don't have the nice timestamps which I need.

Bash command:

node index.js | ts '[%Y-%m-%d %H:%M:%S]' >> $(date --utc +\%Y-\%m-\%d).log 2>&1

Node JS script:

console.log('log');
console.error('error');

What my log file looks like:

[2020-04-15 16:26:10] log

What I want my log file to look like: (timestamps should reflect the exact time when each line logs)

[2020-04-15 16:26:10] log
[2020-04-15 16:26:11] error

Currently the stderr gets logged on the command line instead of making it into the dated log file, which I need. I need it to:

  • append to the log file, not overwrite
  • append async-ly so I can tail -f and see live logging while the script is still running
  • every line should have a prepended timestamp [%Y-%m-%d %H:%M:%S] at the actual time that line gets logged
  • log files should be named by the current day (but it's not necessary)

I've gotten each of these to work with the above bash command with the exception of stderr... so close! Does anyone know how to make it work?

2
  • 1
    Your stderr-to-stdout redirection 2>&1 likely needs to go after the node index.js command – steeldriver Apr 15 '20 at 17:00
  • It appears that you've nailed it. Thank you. – Adam Apr 15 '20 at 17:14
1

Thank you steeldriver for your comment above. Here is the now working bash line:

node index.js 2>&1 | ts '[%Y-%m-%d %H:%M:%S]' >> $(date --utc +\%Y-\%m-\%d).log

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.