How to add timestamp to STDERR redirection

后端 未结 13 2480
感情败类
感情败类 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:36

    Thought I would add my 2 cents worth..

    #!/bin/sh
    
    timestamp(){
      name=$(printf "$1%*s" `expr 15 - ${#1}`)
      awk "{ print strftime(\"%b %d %H:%M:%S\"), \"- $name -\", $$, \"- INFO -\", \$0; fflush() }";
    }
    
    echo "hi" | timestamp "process name" >> /tmp/proccess.log
    

    printf "$1%*s" `expr 15 - ${#1}`
    Spaces the name out so it looks nice, where 15 is the max space issued, increase if desired

    outputs >> Date - Process name - Process ID - INFO - Message

    Jun 27 13:57:20 - process name     - 18866 - INFO - hi
    

提交回复
热议问题