How to log data as JSON with Python

Better Stack Team
Updated on February 3, 2023

If you are new to logging in Python, please feel free to start with our Introduction to Python logging to get started smoothly. Otherwise, here is how to log data as JSON in Python:

The simplest way is to use a custom module:

 
pip install json-logging

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

 
json_logging.init_non_web(enable_json=True)

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

More documentation about this module is provided here. If you would like to have more options when it comes to logging your apps, have a look at our Guide to logging with Loguru, which is the most popular third-party logging framework for Python.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github