Linux

為腳本日誌條目添加時間戳

  • September 9, 2013

目前我有我的 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

如果沒有看到更多您的腳本,我無法告訴您滿足您特定需求的最佳方式。但是,這是一種可以根據您的需要進行調整的通用方式。

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

引用自:https://serverfault.com/questions/536373