我需要从日志文件中提取最后 5 分钟的日志。这是我的日志文件
[2022-02-08 13:26:21:352] [ERROR] [iBus Connection LifeCycle - CCMHost_DummyDevice_Backup_AD2::Management:::NRMCMO_FLPROD2] [com.example]
+ Message: Could not create an administered connection factory: Java heap space
+ Throwable: java.lang.OutOfMemoryError: Java heap space
[2022-02-08 15:09:37:068] [ERROR] [HikariCP connection filler (pool DirectReadConnection.9c292fc0.210e0ac7)] [com.example]
+ Message: Unable to Initialize Connection
+ Throwable: java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
[2022-02-08 15:09:37:068] [ERROR] [HikariCP connection filler (pool DirectReadConnection.9c292fc0.210e0ac7)] [com.example]
+ Message: Unable to Initialize Connection
+ Throwable: java.sql.SQLException: Listener refused the connection with the following error:
ORA-01017, TNS:listener does not currently know of SID given in connect descriptor
[2022-02-08 15:05:04:056] [ERROR] [JMS Session Delivery Thread - The user's password has expired.] [com.example]
我试过用这个,但没有用
awk -v d1="$(date --date="2 hour ago" "+%Y-%m-%d %H:%M:%S:%3N")" -v d2="$(date "+%Y-%m-%d %H:%M:%S:%3N")" '$0 > d1 && $0 < d2 || $0 ~ d2' filelog.log
任何帮助将不胜感激
答案1
这不起作用,因为日志行中的第一个字符是方括号,这会破坏您的比较。如果您只提取日志行的日期部分进行比较,它应该可以工作。注意,我在这里对日期进行了硬编码,以便我可以使用您的示例行。
awk -v d1="2022-02-08 15:04:00" -v d2="2022-02-08 15:08:00" 'd1 < substr($0,2,19) && substr($0,2,19) < d2 || substr($0,2,19) ~ d2' filelog.log
您实际上可以简化命令;由于您只关心 2 小时前以后的时间,因此您可以完全删除“d2”。如果您只关心日期实际出现的行,则可以通过指定匹配的行必须以“[”开头(就像带有日期戳的行一样)来防止与其他行的人为匹配。
awk -v d1="$(date --date="2 hour ago" "+%Y-%m-%d %H:%M:%S:%3N")" '/^\[/ && d1 < substr($0,2,19)' filelog.log
如果您还关心每个匹配日期戳下方的附加行,并且每个有效行条目之间确实有空白行,则可以使用它来修改记录分隔符以获取额外信息并删除“[”的检查,因为其他行是同一条记录的一部分,而不是需要过滤的单独行。
root@2ec99a4edaa9:/tmp# awk -v RS= -v d1="2022-02-08 15:04:00" 'd1 < substr($0,2,19)' filelog.log
[2022-02-08 15:09:37:068] [ERROR] [HikariCP connection filler (pool DirectReadConnection.9c292fc0.210e0ac7)] [com.example]
+ Message: Unable to Initialize Connection
+ Throwable: java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
[2022-02-08 15:09:37:068] [ERROR] [HikariCP connection filler (pool DirectReadConnection.9c292fc0.210e0ac7)] [com.example]
+ Message: Unable to Initialize Connection
+ Throwable: java.sql.SQLException: Listener refused the connection with the following error:
ORA-01017, TNS:listener does not currently know of SID given in connect descriptor
[2022-02-08 15:05:04:056] [ERROR] [JMS Session Delivery Thread - The user's password has expired.] [com.example]
最后,如果您想保留空行以提高输出的可读性,您可以将其添加-v ORS="\n\n"
到 awk 语句中。
总而言之,修改后的命令将如下所示:
awk -v RS= -v ORS="\n\n" -v d1="$(date --date="2 hour ago" "+%Y-%m-%d %H:%M:%S:%3N")" 'd1 < substr($0,2,19)' filelog.log