Registry / observability / logging-json

logging-json

JSON →
library0.6.0pypypi✓ verified 85d ago

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-json
INSTALL
IMPORT
SIG · LOGGING-JSON
L
logging-json
observabilitypythonv0.6.0
Install
1.6s avg
Import
36ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.6.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.038s · 17.8MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 1.6s · import 0.034s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

JSONFormatter
from logging_json import JSONFormatter

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.

import logging from logging_json import JSONFormatter import sys # Configure a logger logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # Create a stream handler (e.g., to stdout) handler = logging.StreamHandler(sys.stdout) # Create a JSON formatter instance # Optional: Customize indentation, ASCII encoding, or datetime format formatter = JSONFormatter( json_indent=2, # Pretty-print JSON json_ensure_ascii=False, # Allow non-ASCII characters directly datetime_format="%Y-%m-%dT%H:%M:%S%z" # Custom datetime format with timezone ) # Set the formatter for the handler handler.setFormatter(formatter) # Add the handler to the logger logger.addHandler(handler) # Log messages with standard fields and extra context logger.info("This is an info message.") logger.warning("Something potentially bad happened.", extra={"user_id": 123, "session": "abc"}) try: raise ValueError("Example error") except ValueError: # logger.exception automatically includes traceback logger.exception("An error occurred during processing.") logger.debug("This message will not be shown as level is INFO.")
Debug
Known issues
breakingVersions 0.5.0 and later of `logging-json` require Python 3.9 or higher. Previous versions supported Python 3.7+.
fix
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`).
affects: 0.5.0+
gotchaThe `extra` dictionary passed to logging calls is merged directly into the top-level JSON object. Ensure values within `extra` are JSON-serializable or expect them to be stringified by default. Complex objects (e.g., custom classes) can lead to serialization errors if not handled.
fix
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`.
affects: All versions
gotchaDirectly using `logging.basicConfig()` with `logging-json` can be tricky as `basicConfig` doesn't easily allow setting a custom formatter with specific parameters beyond a basic format string. You often need to manually configure handlers.
fix
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)`.
affects: All versions
Errors
Common errors & fixes
TypeError: Object of type <YourCustomType> is not JSON serializable
You are attempting to log an object of a custom type or a non-standard Python type (e.g., a `set`) directly in your log message or within the `extra` dictionary, and the default JSON encoder does not know how to serialize it.
fix
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.
Logs are not appearing in JSON format, or default Python log format is shown.
The `JSONFormatter` was either not correctly assigned to a handler, or the handler with the `JSONFormatter` was not added to the logger instance. This can also happen if `basicConfig` overrides custom handler setup.
fix
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.
AttributeError: 'dict' object has no attribute 'str' (or similar error related to extra fields)
In older versions (prior to 0.6.0), there were specific bugs related to how `extra` dictionary values were processed, particularly when they were complex objects or dictionaries themselves. This could lead to unexpected `AttributeError` when the formatter tried to apply `str()` to an already-dict-like object.
fix
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.
Upgrade
Version history
0.6.0latest on PyPI · released Feb 4, 2025
Audit
Dependencies
tzlocalrequiredRequired for timezone-aware datetime formatting in log entries.
Agent activity
14 hits · last 30 days
node
12
OpenAI (training)
2
Resources
logging-json — pip install logging-json · libregistry