如何在 Linux 中读取最后 n 分钟的日志文件



我有以下格式的文件,我想在最后n分钟读取文件。

2019-09-22T04:00:03.052+0000: 774093.613: [GC (Allocation Failure)
Desired survivor size 47710208 bytes, new threshold 15 (max 15)
[PSYoungGen: 629228K->22591K(650752K)] 1676693K->1075010K(2049024K), 0.0139764 secs] [Times: user=0.05 sys=0.00, real=0.01 secs]

我想根据用户要求读取日志文件 x n 分钟,以便我可以根据用户要求监视它最后 30 分钟或 120 分钟。

我已经尝试了以下选项来读取文件,但似乎它没有按预期工作:

awk -F - -vDT="$(date --date="60 minutes ago" +"%Y-%m-%dT%H:%M:%S")" ' DT > $NF,$0' gc-2019-09-13-04-58.log.0.current

另外,在上面的命令"60 分钟前"选项中,我是否尝试将其作为变量传递,例如v1=30date --date="$v1 minutes ago",这个也不起作用?

请建议如何读取此文件的最后x分钟数?

这是一个用于 GNU awk(时间函数和gensub()(。首先是测试数据,第一行中更改了两行数据,年份发生了变化:

2018-09-22T04:00:03.052+0000: 774093.613: [GC (Allocation Failure)
Desired survivor size 47710208 bytes, new threshold 15 (max 15)
[PSYoungGen: 629228K->22591K(650752K)] 1676693K->1075010K(2049024K), 0.0139764 secs] [Times: user=0.05 sys=0.00, real=0.01 secs]
2019-09-22T04:00:03.052+0000: 774093.613: [GC (Allocation Failure)
Desired survivor size 47710208 bytes, new threshold 15 (max 15)
[PSYoungGen: 629228K->22591K(650752K)] 1676693K->1075010K(2049024K), 0.0139764 secs] [Times: user=0.05 sys=0.00, real=0.01 secs]

和awk程序,使用tac将数据向后馈送到:

$ tac file | gawk '
BEGIN {
threshold = systime()-10*60*60 # time threshold is set to 10 hrs
# threshold = systime()-mins*60# uncomment and replace with above 
}                                  # for command line switch
{
if(match($1,/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}/)) {
if( mktime( gensub(/[-T:]/," ","g",substr($1,RSTART,RLENGTH))) < threshold)
exit                   # exit once first beyond threshold time is found
print $0 b                 # output current record and the buffer
b=""                       # reset buffer
} else                         # for non-time starting records:
b=ORS $0 b                 # buffer them
}'

您可以将'之间的程序代码写入文件,例如program.awk并使用tac file | gawk -f program.awk运行它,并通过取消注释BEGIN部分中标记的行并运行以下命令来进一步添加命令行开关:

$ gawk -v mins=10 -f program.awk <(tac file)

获取日志文件的最后 N 行。最重要的命令是"尾巴"。... 连续从文件中获取新行。要在 shell 上实时从日志文件中获取所有新添加的行,请使用命令:tail -f/var/log/mail.log。... 逐行获取结果。... 在日志文件中搜索。... 查看文件的全部内容。

最新更新