Registry / observability / jsonformatter

jsonformatter

JSON →
library0.3.4pypypi✓ verified 85d ago

jsonformatter is a Python library that provides a logging formatter to output log records as JSON objects. It allows for easy customization of LogRecord attributes, enabling users to include or replace fields, for instance, to integrate with log aggregation systems like Logstash. It supports Python 2.7 and Python 3. The latest version, 0.3.4, was released in November 2024, with an irregular but ongoing release cadence.

pip install jsonformatter
INSTALL
IMPORT
SIG · JSONFORMATTER
J
jsonformatter
observabilitypythonv0.3.4
Install
3.1s avg
Import
47ms
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.3.4 · 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.920 runs
installs and imports cleanly · install 0.0s · import 0.050s · 17.9MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 3.1s · import 0.044s · 18MB
16MB installed
● package 16MB
Code
Verified usage

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

basicConfig
from jsonformatter import basicConfig
JsonFormatter
from jsonformatter import JsonFormatter

This quickstart demonstrates two ways to use `jsonformatter`: first, using `basicConfig` for a quick setup, and second, by creating a `JsonFormatter` instance with a custom format string and attaching it to a `StreamHandler`. It also shows how to include extra fields in log messages and handle exceptions.

import logging from jsonformatter import basicConfig, JsonFormatter import sys # Basic configuration for JSON output to console basicConfig(level=logging.INFO) logging.info('Hello, jsonformatter basic config!') # Example with custom formatter and fields FORMAT_STRING = '''{ "time": "asctime", "level": "levelname", "message": "message", "logger_name": "name", "process_id": "process" }''' logger = logging.getLogger('my_app') logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) formatter = JsonFormatter(FORMAT_STRING) handler.setFormatter(formatter) logger.addHandler(handler) logger.info('User logged in', extra={'user_id': 123, 'ip_address': '192.168.1.1'}) try: raise ValueError('Something went wrong') except ValueError: logger.exception('An error occurred during processing.')
Debug
Known issues
gotchaThis `jsonformatter` library (by MyColorfulDays, version 0.3.4) is distinct from `python-json-logger` (by madzak/nhairs), which is a more widely used and actively maintained alternative with a similar purpose. Users often confuse the two. If you're looking for the commonly recommended JSON logger, you might be looking for `python-json-logger`.
fix
Verify the PyPI package name (`jsonformatter` vs `python-json-logger`) and the GitHub repository (`MyColorfulDays/jsonformatter` vs `nhairs/python-json-logger`) to ensure you are installing and using the intended library.
affects: All versions
gotchaWhen logging objects that are not natively JSON serializable (e.g., custom class instances, `datetime` objects without special handling), `jsonformatter` may raise `TypeError` unless a custom `default` or `cls` parameter is provided to the `JsonFormatter` constructor. This is a common pitfall in Python's `json` module usage.
fix
Pass a `default` callable or a custom `json.JSONEncoder` subclass via the `cls` parameter to the `JsonFormatter` constructor to define how non-serializable objects should be converted. For example, `JsonFormatter(format_string, default=str)` will convert such objects to their string representation.
affects: All versions
deprecatedWhile `jsonformatter` officially supports Python 2.7, Python 2 has reached its End-of-Life (EOL) and is no longer maintained. Using it in new projects or maintaining existing Python 2 projects carries security and compatibility risks.
fix
For new development, use Python 3 exclusively. For existing projects, consider migrating to Python 3. `jsonformatter` is also compatible with Python 3, so ensure your environment uses a supported Python 3 version.
affects: All versions supporting Python 2.7 (>=0.2.x)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'jsonformatter'
The `jsonformatter` library is not installed in your Python environment or there's a typo in the import statement.
fix
Ensure the library is installed using pip: `pip install jsonformatter`.
AttributeError: module 'jsonformatter' has no attribute 'Formatter'
You are trying to access a class or attribute named 'Formatter' (or similar incorrect casing/name) from the `jsonformatter` module, but the main class for logging is `JsonFormatter`.
fix
Use the correct class name for the logging formatter: `from jsonformatter import JsonFormatter`.
TypeError: Object of type X is not JSON serializable
You are trying to log a `LogRecord` attribute that contains an object (e.g., a custom class instance, a set, or other non-primitive type) that the standard `json` module does not know how to convert into a JSON string.
fix
You need to provide a custom JSON encoder to `JsonFormatter` to handle non-serializable objects. This can be done by passing a `json_default` function or a `cls` (JSONEncoder subclass) parameter to `JsonFormatter` that defines how to serialize these types.
KeyError: 'SomeLogRecordAttribute'
When using a custom format string (e.g., in a dictionary configuration for logging), you've specified a `LogRecord` attribute that doesn't exist or isn't available in the current logging context.
fix
Review your `format` string or dictionary configuration to ensure all specified `LogRecord` attributes (like `%(levelname)s`, `%(message)s`, `%(name)s`, or custom attributes) are valid and present in the log record. Ensure any custom attributes are properly added to the `LogRecord.extra` dictionary if you intend to include them.
Upgrade
Version history
0.3.4latest on PyPI · released Nov 21, 2024
Audit
Dependencies

No dependency data recorded yet.

Agent activity
10 hits · last 30 days
node
8
OpenAI (training)
2
Resources
jsonformatter — pip install jsonformatter · libregistry