[英]Format and pretty print log via tail
我有這個日志文件,我經常檢查它,由於它的格式,打印出來后更容易閱讀。 我想這樣做。
登錄文件,如:
2019-07-04T09:53:04-07:00 some.package.placeholder.stderr {"log": "The content", "foo": "bar", "baz": "blah"}
2019-07-04T10:15:37-07:00 some.package.placeholder.stderr {"log": "I'm actually", "foo": "bar", "baz": "blah"}
2019-07-04T10:15:37-07:00 some.package.placeholder.stderr {"log": "Interested on", "foo": "bar", "baz": "blah"}
我想做類似的事情
tail -f myLogFile | grep [...?...] | jq '.log'
所以當尾隨我得到:
The content
I'm actually
Interested on
甚至:
2019-07-04T09:53:04-07:00 The content
2019-07-04T10:15:37-07:00 I'm actually
2019-07-04T10:15:37-07:00 Interested on
使用GNU grep -o
:
$ tail file | grep -o '{[^}]*}' | jq -r '.log'
The content
I'm actually
Interested on
任何awk:
$ tail file | awk 'sub(/.*{/,"{")' | jq -r '.log'
The content
I'm actually
Interested on
$ tail file | awk '{d=$1} sub(/.*{/,""){$0="{\"date\": \""d"\", " $0} 1' | jq -r '.date + " " + .log'
2019-07-04T09:53:04-07:00 The content
2019-07-04T10:15:37-07:00 I'm actually
2019-07-04T10:15:37-07:00 Interested on
最后一個通過將輸入中的日期字段合並到json中來工作,然后jq可以選擇它並將其與日志字段一起打印。
如果日志行由制表符分隔,則可以讀取原始行並在制表符上拆分行。 然后您可以解析json並過濾到您的hearts內容,並在必要時進行重組。
$ tail -f myLogFile | jq -Rr 'split("\t") | [.[0], (.[2] | fromjson.log)] | join("\t")'
2019-07-04T09:53:04-07:00 The content
2019-07-04T10:15:37-07:00 I'm actually
2019-07-04T10:15:37-07:00 Interested on
這是我使用的一個東西,可以在管道和文件 args 中使用:
cat /usr/local/bin/j2t
#!/bin/bash
function usage {
cat <<EOF
Usage:
$0 <json filename>
or
tail -F <json filename> | $0
EOF
}
if (($# == 0)); then
{
sed "s/@\(timestamp\)/\1/" | jq -r '[.timestamp, .pri.facility, .pri.severity, .message] | join("\t")'
} < /dev/stdin
else
if [ -r "$1" ] ; then
sed "s/@\(timestamp\)/\1/" $1 | jq -r '[.timestamp, .pri.facility, .pri.severity, .message] | join("\t")'
else
help
fi
fi
例如:(如果您的 daemon.log 是 json)
j2t /var/log/daemon.log
level: 63, builder: awillia2)
2021-08-14T00:00:06.820642+00:00 daemon INFO Starting Run Clamscan...
2021-08-14T00:00:06.846405+00:00 daemon INFO Started Run Clamscan.
可能應該重新格式化時間,它有點長。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.