Skip to main content

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

Project description

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

philiprehberger_json_logger-0.3.0.tar.gz (190.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

philiprehberger_json_logger-0.3.0-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

Details for the file philiprehberger_json_logger-0.3.0.tar.gz.

File metadata

File hashes

Hashes for philiprehberger_json_logger-0.3.0.tar.gz
Algorithm Hash digest
SHA256 44c307b1739a485ba17c71afda6e7b3795aa775d31abc9ae75c7ca8ed29b10f0
MD5 512bbb1a199485c01919c16020db6d38
BLAKE2b-256 343d9c006528ae90ba2b0f85c0cd1ff9466ebb5434fa0e360840bf64b76324a2

See more details on using hashes here.

File details

Details for the file philiprehberger_json_logger-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for philiprehberger_json_logger-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6853bb45e2630ed4ac33c4eed39c299c94d400a7a3b80f8ffdf1e8536d886b16
MD5 0d888c5a56cd57d05f74a59af3d43b87
BLAKE2b-256 97631bc64efc34c056952d6f360b86066e81a7cbd9ac3c453e3d094d3888bbef

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page