Search code examples
bashcron

Log output and error from cron script to custom file with timestamp


I'm trying to log both stdout and stderr from my cron task to a custom log file. If there is no output or error, I do not want to log anything. If there is either output or error, I want to log it to a new line and prefix it with the current timestamp.

I've tried the following

myscript 2>&1 | echo "$(cat -)" | ts >> cron.log

This gets me almost what I want. It will log both output and errors from myscript, prefix them with the current timestamp and put them on a new line. The problem is that if myscript produces no output, then because echo produces a new line, I'll get a log entry with just the timestamp on a new line.

I want to do this all on the cron line. I do not want to have to modify myscript.


Solution

  • I suggest to use sed:

    myscript 2>&1 | ts | sed '$a\' >> cron.log
    

    This adds \n at the end of the file only if it doesn’t already end with a newline. -- l0b0