How to log data as JSON with Python

Better Stack Team
Updated on May 4, 2022

The simplest way is to use a custom module:

pip install json-logging
Copied!

To initialize the logger when not using the web framework, use this line of code:

json_logging.init_non_web(enable_json=True)
Copied!

For web applications, replace _non_web with the name of framework. (_flask, _sanic,...)

More documentation about this module is provided here.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack