我需要從日誌檔案中提取最後 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