python-json-logger icon indicating copy to clipboard operation
python-json-logger copied to clipboard

How can I output the json with newlines?

Open pmcl77 opened this issue 3 years ago • 2 comments

Im simply setting up the jsonformatter with:

streamformat = jsonlogger.JsonFormatter("%(asctime)s %(levelname)s %(levelno)s %(module)s %(message)s %(lineno)s ")

It will output the json all in one line. Is there an option to have a "pretty" output somehow like you showed in your example output?

pmcl77 avatar Dec 31 '21 14:12 pmcl77

If you want it in a pretty output from stdout, you could run your server and pipe it into jq. In my case I ran something like uvicorn main:app --reload | jq

If you have a mix of json and non-json lines I found the following works:

uvicorn main:app --reload | jq -R -r '. as $line | try fromjson catch $line'

jdkern11 avatar Jul 14 '22 20:07 jdkern11

Unfortunately the jq trick didnt seem to work for me, when debugging in cli, stack traces put invalid json on stdout. However setting indent on the constructor seems to work fine:

formatter = jsonlogger.JsonFormatter(json_indent=2)

See Allows pretty printing of JSON messages w/ cls kwarg #45

damobrisbane avatar Jul 28 '22 21:07 damobrisbane