Skip to main content

philiprehberger-json-logger

Tests PyPI version Last updated

Drop-in structured JSON logging for Python using the stdlib logging module.

Installation

pip install philiprehberger-json-logger

Usage

Quick setup

from philiprehberger_json_logger import setup

setup(level="DEBUG")

import logging
logging.info("Server started", extra={"port": 8080})
# {"timestamp": "2026-03-13T12:00:00+00:00", "level": "INFO", "message": "Server started", "logger": "root", "module": "app", "line": 5, "port": 8080}

Named logger

import logging
from philiprehberger_json_logger import setup

logger = logging.getLogger("myapp")
setup(level="INFO", logger=logger)

logger.warning("Disk usage high", extra={"usage_pct": 91.3})

Static extra fields

from philiprehberger_json_logger import setup

setup(level="INFO", extra_fields={"service": "api", "env": "production"})

Every log entry will include "service": "api" and "env": "production".

Field redaction

from philiprehberger_json_logger import setup

setup(level="INFO", redact_fields={"password", "token", "secret"})

import logging
logging.info("Login", extra={"user": "alice", "password": "s3cret"})
# password field will appear as "***"

Redaction works recursively on nested dicts.

Scoped context

import logging
from philiprehberger_json_logger import setup, log_context

setup(level="INFO")

with log_context(request_id="abc-123", user="alice"):
    logging.info("Processing request")
    # log entry includes request_id and user fields

    with log_context(step="validation"):
        logging.info("Validating input")
        # log entry includes request_id, user, and step fields

Clearing context

import logging
from philiprehberger_json_logger import setup, log_context, clear_context

setup(level="INFO")

with log_context(user="alice"):
    logging.info("First")  # includes user

    clear_context()
    logging.info("Second")  # no user field

Useful in test teardown or framework reset hooks where the with-block scoping doesn't fit.

Custom handler with JsonFormatter

import logging
from philiprehberger_json_logger import JsonFormatter

handler = logging.FileHandler("app.log")
handler.setFormatter(JsonFormatter(extra_fields={"service": "worker"}, redact_fields={"token"}))

logger = logging.getLogger("worker")
logger.addHandler(handler)
logger.setLevel(logging.INFO)

Pretty-printed output

import logging
from philiprehberger_json_logger import JsonFormatter

handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter(indent=2))

logger = logging.getLogger("dev")
logger.addHandler(handler)
logger.setLevel(logging.INFO)

logger.info("Pretty")
# {
#   "timestamp": "2026-05-30T12:00:00+00:00",
#   "level": "INFO",
#   "message": "Pretty",
#   ...
# }

API

Name Description
JsonFormatter(*, extra_fields=None, redact_fields=None, indent=None) Logging formatter that outputs JSON lines. extra_fields is a dict of static fields merged into every entry. redact_fields is a set of field names replaced with "***". indent (int or None) is forwarded to json.dumps for pretty-printed output; None produces compact single-line JSON.
setup(level="INFO", *, extra_fields=None, redact_fields=None, logger=None) Configure a logger with JSON output. Defaults to the root logger. Clears existing handlers.
log_context(**kwargs) Context manager that injects fields into all log entries within the block. Supports nesting.
clear_context() Clear all currently-bound log_context() fields. Useful in test teardown or framework reset hooks. No-op if nothing is bound.

JSON output fields

Field Description
timestamp ISO 8601 UTC timestamp
level Log level name (DEBUG, INFO, WARNING, ERROR, CRITICAL)
message Formatted log message
logger Logger name
module Source module name
line Source line number
exception Full traceback string (only present when logging an exception)

Any extra={} kwargs passed to the log call are merged into the top-level JSON object. Static extra_fields from the formatter and active log_context() fields are also merged.

Development

pip install -e .
python -m pytest tests/ -v

Support

If you find this project useful:

⭐ Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

Release files for philiprehberger-json-logger 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for philiprehberger-json-logger 0.3.0
File Size Uploaded
philiprehberger_json_logger-0.3.0.tar.gz 190.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for philiprehberger-json-logger 0.3.0
File Interpreter ABI Platform
philiprehberger_json_logger-0.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 196.7 kB

Release files / philiprehberger_json_logger-0.3.0.tar.gz

Download URL philiprehberger_json_logger-0.3.0.tar.gz
Size 190.8 kB
Tags Source
SHA-256 checksum
How to use checksums
44c307b1739a485ba17c71afda6e7b3795aa775d31abc9ae75c7ca8ed29b10f0
BLAKE2b-256 checksum
How to use checksums
343d9c006528ae90ba2b0f85c0cd1ff9466ebb5434fa0e360840bf64b76324a2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Release files / philiprehberger_json_logger-0.3.0-py3-none-any.whl

Download URL philiprehberger_json_logger-0.3.0-py3-none-any.whl
Size 6.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6853bb45e2630ed4ac33c4eed39c299c94d400a7a3b80f8ffdf1e8536d886b16
BLAKE2b-256 checksum
How to use checksums
97631bc64efc34c056952d6f360b86066e81a7cbd9ac3c453e3d094d3888bbef
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page