|
/Coding/bash:
Add a Timestamp to Your Logging
Suppose you have various bits of code executing in cron, sending their output to user-defined log files, ie. some cron entries as follows,
*/2 * * * * /path/to/a/script.sh >> /some/logging/directory/cron.output 2>&1and you want a generalized way of tagging each log entry with a time stamp. The solution is fairly simple, but the bits are sufficiently hard to track down and not all available in one place, so I thought I would document it.... Create this script, lets call it timestamp.sh:
#!/bin/bash
# this script prepends a time stamp to the first line of piped input.
stamp=$(date "+%F %R:%S")
echo -n $stamp
echo -n " "
while read line; do
# print the first line of piped input
echo ${line[0]}
done
and then use a cron entry as follows:
*/2 * * * * /path/to/a/script.sh 2>&1 | /path/to/timestamp.sh >> /logging/directory/cron.output 2>&1Ie. The output of script.sh is piped to timestamp.sh, where the first line is prepended with the timestamp, and then the time-stamped line is added to cron.output. Thanks to [1].
[1] http://www.linuxquestions.org/questions/linux-software-2/bash-scripting-pipe-input-to-script-vs-$1-570945/
posted at: 16:19 | path: /Coding/bash | permanent link to this entry