splunk中如何解析JSON、並做處理

最近有個splunk需求,程式所產生的log中想埋入JSON格式的內容。後續需要由splunk解析該JSON內的資訊、以分析、或相關警示的處理。

首先說明此次splunk中的log格式,舉三筆示意的log如下
[demo][ERROR][2019-11-08 16:39:08][{"api":{"id":"tester","task":"test"}}][my.domain.com][CLI][myphp.php]
[demo][ERROR][2019-11-08 16:46:57][{"api":{"id":"tester1","task":"test"}}][my.domain.com][CLI][myphp.php]
[demo][ERROR][2019-11-08 18:39:08][{"api":{"id":"tester3","task":"test"}}][my.domain.com][CLI][myphp.php]

當中的[{"api":{"id":"tester1","task":"test"}}]已經在slplunk中先定義為欄位,欄位名稱為MSG

下面的語法,是將欄位MSG做JSON解析
index="mylog" | spath input=MSG

如能正常完成解析,就可以將JSON的內容做後續的處理。下面舉三個簡單的範例…
範例語法1:搜尋在JSON格式內容中id為tester的紀錄
index="mylog" | spath input=MSG | search api.id="tester"

範例語法2:計數各個id有幾筆
index="mylog" | spath input=MSG | stats count by api.id

範例語法3:統計某段時間內,各個id於每分鐘內出現的次數並畫出圖表
index="mylog" | spath input=MSG | timechart span=5m count by api.id
範例產生的圖表如下~
splunk-json-parse
splunk-json-parse

對了,如果資料有問題無法正常做JSON解析,splunk就不會有結果、但似乎也不會產生錯誤訊息....這點,讓我測試時浪費了一點時間~


參考資料



留言