logging-json is a Python library that provides a JSON formatter for the standard `logging` module, allowing applications to output logs in a structured JSON format. This is particularly useful for centralized logging systems and machine readability. The current version is 0.6.0, and it generally maintains an active release cadence with periodic updates for bug fixes and new features.
pip install logging-jsonVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up a basic logger with `logging-json`. It configures a `StreamHandler` to output JSON formatted logs to standard output. It also shows how to include extra dictionary fields in your logs, which are automatically merged into the root JSON object.
Ensure your project's Python interpreter is at least 3.9. If you need to support older Python versions, you must pin `logging-json` to a version prior to 0.5.0 (e.g., `logging-json<0.5`).
Always pass JSON-serializable types (strings, numbers, booleans, lists, dicts) in `extra`. For complex objects, convert them to a serializable representation (e.g., `str(obj)` or `obj.to_dict()`) before passing them, or implement a custom JSON encoder within `JSONFormatter`.
Instead of `logging.basicConfig()`, create and configure `logging.StreamHandler` or `logging.FileHandler` instances, create a `JSONFormatter`, and then explicitly attach the formatter to the handler using `handler.setFormatter(formatter)` and the handler to the logger using `logger.addHandler(handler)`.
Before logging, convert the object to a basic JSON-serializable type (e.g., `str(obj)`, `list(obj_set)`, `obj.to_dict()`). Alternatively, for more advanced cases, you can provide a custom `json_encoder` argument to `JSONFormatter` to handle specific types.
Verify that `handler.setFormatter(json_formatter)` was called with your `JSONFormatter` instance and that `logger.addHandler(handler)` was called for each logger you intend to use. Avoid using `logging.basicConfig()` after custom handler setup, or ensure your `basicConfig` setup explicitly configures the desired handler and formatter.
Upgrade `logging-json` to version 0.6.0 or higher, which includes fixes for how `extra` fields are handled. Always ensure the values in your `extra` dictionary are fundamentally JSON-serializable (strings, numbers, lists, etc.) to prevent such issues.