Last active
March 5, 2021 15:32
-
-
Save gaqzi/9593e79891b7593ef43d2e92ee15cf75 to your computer and use it in GitHub Desktop.
To pretty-print logs of JSON. Can be used like: `docker-compose logs -f myapp | json_pp_stream.py`. Made a Go version as well: https://github.com/gaqzi/log-viewer/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import json | |
import sys | |
try: | |
from pygments import highlight, lexers, formatters | |
def json_formatter(line: str) -> str: | |
return highlight(line, lexers.JsonLexer(), formatters.TerminalFormatter()) | |
except ImportError: | |
def json_formatter(line: str) -> str: | |
return line | |
def pp_line(line: str) -> str: | |
original = line | |
prefix = "" | |
if line[0] != "{": | |
split = line.split(" : ", maxsplit=1) | |
if len(split) == 2: | |
prefix, line = split | |
line = line.lstrip() | |
if line[0] != "{": | |
return original.rstrip() | |
output = [] | |
indent = " " | |
for line in json.dumps(json.loads(line), indent=4).splitlines(): | |
output.append(f"{indent}{line}") | |
return f"{prefix}\n" + json_formatter('\n'.join(output)) | |
if __name__ == '__main__': | |
for line in sys.stdin: | |
print(pp_line(line)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment