加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 为脚本日志条目添加时间戳

发布时间:2020-12-14 02:39:27 所属栏目:Linux 来源:网络整理
导读:目前,我使用exec 22 2 21 1 1 $log 2 1将我的bash脚本写入stderr和stdout到日志文件.我想为每个条目添加一个时间戳,但我还没有找到一个简单的方法来做到这一点.理想情况下,对当前命令进行简单的更改,然后在其余部分之前将时间写在同一行上. 这是我正在使用命
目前,我使用exec 22>& 2 21>& 1 1> $log 2>& 1将我的bash脚本写入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 %sn' "$(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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读