madzak / python-json-logger

Json Formatter for the standard python logger
BSD 2-Clause "Simplified" License
1.7k stars 231 forks source link

How can I output the json with newlines? #126

Closed pmcl77 closed 1 year ago

pmcl77 commented 2 years ago

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?

jdkern11 commented 1 year ago

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'

damobrisbane commented 1 year ago

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