图片来源:https://www.pixiv.net/artworks/42320059
大多日志都会在行首添加时间信息,通过在awk脚本内调用date
命令把时间信息转换为时间戳进行比较实现日志截取
以linux启动日志为例,以空格为分隔符的话,前三个字段为时间信息
boot.log(journalctl -b 的部分输出结果)Nov 11 12:51:44 archlinux kernel: microcode: microcode updated early to revision 0xf0, date = 2021-11-12 Nov 11 12:51:44 archlinux kernel: Linux version 6.0.2-arch1-1 (linux@archlinux) (gcc (GCC) 12.2.0, GNU ld (GNU Binutils) 2.39.0) #1 SMP PREEMPT_DYNAMIC Sat, 15 Oct 2022 14:00:49 +0000 Nov 11 12:51:44 archlinux kernel: Command line: initrd=\intel-ucode.img initrd=\initramfs-linux.img root=PARTUUID=10b213f0-2653-4c20-af2f-3195c1667158 zswap.enabled=0 rootflags=subvol=@ rw intel_pstate=no_hwp rootfstype=btrfs ...
下面的脚本截取 2022-11-11 12:51:44 ~ 2022-11-11 12:52:44 这一分钟内的日志(执行:./logfilter.awk boot.log
)
logfilter.awk#!/usr/bin/awk -f BEGIN{ stime = to_ts("2022-11-11 12:51:44") etime = to_ts("2022-11-11 12:52:44") } { ts = to_ts($1" "$2" "$3) if (ts >= stime && ts <= etime) print $0 } function to_ts(time){ "date -d \""time"\" +%s" | getline ts return ts }
或者略微修改一下,通过命令行传入起止时间
logfilter.awk#!/usr/bin/awk -f BEGIN{ stime = to_ts(st) etime = to_ts(ed) } { ts = to_ts($1" "$2" "$3) if (ts >= stime && ts <= etime) print $0 } function to_ts(time){ "date -d \""time"\" +%s" | getline ts return ts }
用法
awk -f logfilter.awk -v st="2022-11-11 12:51:44" -v ed="2022-11-11 12:52:43" boot.log

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。