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

时间:2019-09-22 07:24:18

标签: linux shell

我有以下格式的文件,并且我想在最近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分钟内如何读取此文件?

2 个答案:

答案 0 :(得分:2)

这是GNU awk(time functionsgensub())中的一个。首先是测试数据,第一个数据中带有年份的两行更改了:

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)

答案 1 :(得分:0)

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