如何在连续写入的日志文件的每一行中添加日期字符串 [英] How to add date string to each line of a continuously written log file
本文介绍了如何在连续写入的日志文件的每一行中添加日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个长时间运行的程序,该程序连续写入日志文件-怎么可能不考虑任何缓冲问题,而使用linux脚本在写入该文件的每一行中添加一个日期字符串呢?
Having a long running program that continuously writes to a logfile - how is it possible, disregarding any buffering issues, to add a date string to each line written to that file using a linux script?
我会想像这样的东西:
tail -f logfile | ADD_DATE_TO_EACH_LINE > logfile2
输入内容如下:
abc
def
ghi
jkl
输出应类似于以下内容:
The output should be similar to that:
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
推荐答案
使用perl:
command 2>&1 | perl -pe 'print scalar(localtime()), " ";'
使用gawk:
command 2>&1 | awk '{ print strftime(), $0; fflush() }'
对于您的特定示例,将command
替换为tail -f logfile
.或者,也许您可以将原始程序的stdout/stderr重定向到上述管道.
Replace command
with tail -f logfile
for your specific example. Or, perhaps you could just redirect the original program's stdout/stderr to the above pipe.
这篇关于如何在连续写入的日志文件的每一行中添加日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文