Home > Net >  Prepend timestamp to stderr before logging
Prepend timestamp to stderr before logging

Time:01-12

I am trying to figure out how to prepend the timestamp to stderr before it gets logged to a file.

I have the following

sudo apt-get -y update 2>> error.log

sudo apt-get -y upgrade 2>> error.log

But have not had any luck getting the timestamp prepended

CodePudding user response:

(
    sudo apt-get -y update
    sudo apt-get -y upgrade
) 2> >(while IFS= read -r line; do echo "$(date): $line"; done > error.log)

Group all the commands in a subshell and use process substitution to redirect their combined output to a loop. The loop can read a line at a time and echo them back with timestamps prepended.

This technique is nice because the individual apt-get commands don't need to be modified, and > error.log is only needed once at the end.

See also:

CodePudding user response:

sudo apt-get -y update 2>> ( while read line; do echo "$(date): ${line}"; done >> error.log)
sudo apt-get -y upgrade 2>> ( while read line; do echo "$(date): ${line}"; done >> error.log)
  •  Tags:  
  • Related