将时间戳添加到脚本日志条目

将时间戳添加到脚本日志条目

目前,我有一个 bash 脚本,用于exec 22>&2 21>&1 1>$log 2>&1将 stderr 和 stdout 写入日志文件。我想为每个条目添加一个时间戳,但我还没有找到简单的方法来做到这一点。理想情况下,只需对当前命令进行简单更改,并将时间写在其余命令之前的同一行上。

下面是我使用该命令的脚本:

#!/bin/bash

#This script takes the server to rysnc as an argument. You can also tell 
#the script to check the server_status.txt file.
#
#Example: /path/to/script/sync.sh grail true
#
#The arguments are order senstive. The server name must come before the status
#check value.

#Logfile
LOG=/var/log/sync.log

DIRECTORYS="auth/ keys/ log/mailwhen/ intranet/ www/calmaa/data/ www/admatch/data/ www/sfhsa/data/ www/hfa3_org www/padmatch/ www/serverdown/"

if [ "x$2" == "xfalse" ]; then
    return 0
elif [ "x$2" == "xtrue" ]; then
    if [ `cat /srv/www/wan*/server_status.txt` == "primary" ]; then
        exit 0
    fi
else
    echo "Please use \"true\" or \"false\" for the second value." 
    exit 1
fi

# Copy stdout and stderr, and then open the logfile
exec 22>&2 21>&1 1>$log 2>&1
# Here is how to restore stdout and stderr:
# exec 2>&22 1>&21

for DIRECTORY in $DIRECTORYS; do
    rsync -azu --delete --bwlimit=500 $1:/srv/$DIRECTORY  /srv/$DIRECTORY
done

答案1

在没有看到更多脚本的情况下,我无法告诉您最适合您特定需求的方法。不过,这是一种可以根据您的需求进行调整的通用方法。

exec > >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line"; done)

输出的每一行文本都会在前面加上发生时间的时间戳。输出将如下所示:

2013-09-04 21:32:14-05:00 An event occurred and this is the message
2013-09-04 21:32:37-05:00 Some time passed, another event produced a message

答案2

使用以下方式编辑流sed

sed "s/^/$(date -u) /"

使用管道:

[root@giomacdesk ~]# cat test.txt 
asd1
asd2
[root@giomacdesk ~]# cat test.txt |sed "s/^/$(date -u) /"
ოთხ სექ  4 19:00:53 UTC 2013 asd1
ოთხ სექ  4 19:00:53 UTC 2013 asd2
[root@giomacdesk ~]# 

相关内容