如何将日期字符串添加到连续写入的日志文件的每一行

时间:2011-06-16 16:53:24

标签: linux bash string logging csh

有一个长时间运行的程序,不断写入日志文件 - 如何使用Linux脚本为每个写入该文件的行添加日期字符串,忽略任何缓冲问题?

我会想象这样的事情:

tail -f logfile | ADD_DATE_TO_EACH_LINE > logfile2

输入将是这样的:

abc
def
ghi
jkl

输出应类似于:

2011-06-16 18:30:59 abc
2011-06-16 18:31:00 def
2011-06-16 18:35:21 ghi
2011-06-16 18:40:15 jkl

8 个答案:

答案 0 :(得分:22)

使用perl:

command 2>&1 | perl -pe 'print scalar(localtime()), " ";'

gawk:

command 2>&1 | awk '{ print strftime(), $0; fflush() }'

command替换为tail -f logfile以获取具体示例。或者,也许您可​​以将原始程序的stdout / stderr重定向到上面的管道。

答案 1 :(得分:6)

尝试

tail -f logfile | while read line; do echo `date` "$line" ; done

答案 2 :(得分:5)

你可以试试这个

cat /etc/motd | xargs -d"\n" -I {} date +"%Y-%m-%d %H:%M:%S {}"

示例输出:

2013-02-26 15:13:57 
2013-02-26 15:13:57 The programs included with the Debian GNU/Linux system are free software;
2013-02-26 15:13:57 the exact distribution terms for each program are described in the
2013-02-26 15:13:57 individual files in /usr/share/doc/*/copyright.
2013-02-26 15:13:57 
2013-02-26 15:13:57 Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
2013-02-26 15:13:57 permitted by applicable law.

答案 3 :(得分:1)

有点冗长,但这就是我想出来的:

tail -f logfile | sed -u 's/%/%%/g' | xargs -I {} date +"%Y-%m-%d %H:%M:%S {}"

答案 4 :(得分:1)

存在专门用于此目的的工具,它是ts(请参阅man ts

例如,使用您的日志文件:

tail -f logfile | ts '%Y-%m-%d %H:%M:%S'

当然,还可以与在标准输出上编写的任何软件配合使用

./blabla | ts '%Y-%m-%d %H:%M:%S'

如果需要,可以用%.S代替%S来增加亚秒精度

答案 5 :(得分:0)

您是否可以将长时间运行的程序配置为将其输出写入标准输出而不是日志文件?在这种情况下,很容易将输出传递给首先写入当前时间戳然后写入条目的脚本。

如果这是不可能的,可能有助于定期(例如每秒)读取日志文件内容,将每行复制到另一个文件(添加当前时间戳),然后删除日志文件。但是,这可能会导致在读取和删除文件之间写入丢失的日志文件:(

答案 6 :(得分:0)

或者您可以使用python ...

cat /dev/urandom | python -c "from __future__ import print_function; import sys; import datetime; map(lambda x: print(datetime.datetime.now(), x), [line for line in sys.stdin.readlines()])"

或使用gnu屏幕

screen -a ls -lh -L -U -X command

首先,您需要在〜/ .screenrc上启用日志记录和时间戳。

logfile /tmp/screen-%S-%n.log
logtstamp on

答案 7 :(得分:0)

我看到了 elsewhere 一个建议,如果及时性很重要,那么应该避免从 BASH 调用其他程序并使用内置程序:

printf '%(%F %T)T\n'

%T 是来自 date(参见 man date)的相同格式字符串,AFAICT。 示例:

output="Err, Miss Crabapple, I just ate my worm!"; \
printf '\n%(%F %s)T'; printf "%s \n" " $output"

将输出:

2021-03-28 1616894012 Err, Miss Crabapple, I just ate my worm!

我刚刚注意到对该链接的评论建议使用 gawk for timestamp top speeds