Skip to content

Instantly share code, notes, and snippets.

@jiang-wei
Last active March 20, 2020 15:12
Show Gist options
  • Save jiang-wei/1a7724b53bfcd83aec82daadb3dbb6ec to your computer and use it in GitHub Desktop.
Save jiang-wei/1a7724b53bfcd83aec82daadb3dbb6ec to your computer and use it in GitHub Desktop.
decode json log of kubernetes log
#!/usr/bin/env python
#
# save to $PATH as "jslog"
# and use as:
# kubectl logs xxx | jslog
#
import sys
import json
import argparse
from datetime import datetime
def convert_timestamp(timestamp):
sec = int(timestamp['seconds'])
nano = timestamp['nanos']
s = datetime.fromtimestamp(sec).isoformat()
return s + '.' + str(nano)[0:3]
def main(args):
for line in sys.stdin:
try:
d = json.loads(line.rstrip('\n'))
ts = ""
if args.timestamp:
ts = convert_timestamp(d['timestamp'])
print(ts + " " + d['message'])
else:
print(d['message'])
except:
print(line.rstrip('\n'))
parser = argparse.ArgumentParser();
parser.add_argument('-t', '--timestamp', default=False, action='store_true', help="print timestamp")
args = parser.parse_args()
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment