How to add timestamp to STDERR redirection

后端 未结 13 2521
感情败类
感情败类 2020-11-28 05:10

In bash/ksh can we add timestamp to STDERR redirection?

E.g. myscript.sh 2> error.log

I want to get a timestamp written on the log too.

13条回答
  •  野性不改
    2020-11-28 05:31

    Rather than writing a script to pipe to, I prefer to write the logger as a function inside the script, and then send the entirety of the process into it with brackets, like so:

     # Vars    
     logfile=/path/to/scriptoutput.log
    
     # Defined functions
     teelogger(){
       log=$1
       while read line ; do
         print "$(date +"%x %T") :: $line" | tee -a $log
       done
     }
    
    
    # Start process
    {
    
    echo 'well'
    sleep 3
    echo 'hi'
    sleep 3
    echo 'there'
    sleep 3
    echo 'sailor'
    
    }  |  teelogger $logfile
    

提交回复
热议问题