使用类似 printf 的输出拖尾 JSON 日志文件



尝试使用以下示例内容tail -f日志文件。

{"name":"common","hostname":"kgilbert-mac.corp.realpage.com","pid":65184,"level":30,"msg":"iOT API listening at http://[::]:8080","time":"2017-01-11T00:20:26.359Z","v":0}
{"name":"common","hostname":"kgilbert-mac.corp.realpage.com","pid":65185,"level":30,"msg":"iOT API listening at http://[::]:8080","time":"2017-01-11T00:20:28.942Z","v":0}
{"name":"common","hostname":"kgilbert-mac.corp.realpage.com","pid":65187,"level":30,"msg":"iOT API listening at http://[::]:8080","time":"2017-01-11T00:20:30.221Z","v":0}

但是,我希望尾巴的输出不是每行上的实际 JSON 字符串,而是它的 printf 和有限版本。

所以也许像这样

name: common | hostname: localhost | pid: 65187 | level: 30 | msg: iOT API listening at http://[::]:8080 | time: 2017-01-11T00:20:30.221Z

试试这个:

tail json.txt | awk -F "," '{OFS="t"; print $1,$2,$3,$4,$5,$6 }'

请注意,JSON strint 可以在其项目的键和值中包含","。为了安全起见,我强烈建议您使用python将json转换为像CVS一样的共振峰,这更容易。

这是一个可以用作实用程序的 python 骨架(通过组合堆栈溢出答案获得):

#!/usr/bin/python
import time
import subprocess
import select
import json
from pprint import pprint
def processIt( string ):
    j = json.loads( string )
    for k in j:
        print "%s : %s" % ( k, j[k] )
f = subprocess.Popen(['tail','-F',"foo"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p = select.poll()
p.register(f.stdout)
while True:
    if p.poll(1):
        try:
            processIt(f.stdout.readline())
        except:
            pass
    time.sleep(1)

这对于jq来说相对简单

tail -f | jq -r '"name: (.name) | hostname: (.hostname) | pid: (.pid) | level: (.level) | msg: (.msg) | time: (.time)"'

最新更新