通过tail格式化和漂亮的打印日志

unm*_*dio 4 logging grep json tail jq

我有这个日志文件,我经常检查它,由于它的格式,打印出来后更容易阅读。我想这样做。

登录文件,如:

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"}
Run Code Online (Sandbox Code Playgroud)

我想做类似的事情

tail -f myLogFile | grep [...?...] | jq '.log'
Run Code Online (Sandbox Code Playgroud)

所以当尾随我得到:

The content
I'm actually
Interested on
Run Code Online (Sandbox Code Playgroud)

甚至:

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
Run Code Online (Sandbox Code Playgroud)

Ed *_*ton 5

使用 GNU grep -o

$ tail file | grep -o '{[^}]*}' | jq -r '.log'
The content
I'm actually
Interested on
Run Code Online (Sandbox Code Playgroud)

使用任何 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
Run Code Online (Sandbox Code Playgroud)

最后一个的工作原理是将输入中的日期字段合并到 json 中,这样 jq 就可以选择并使用日志字段打印它。