Skip to main content

Table of Contents generated with DocToc

Logger extras for simplified structured logging.

django-logger-extra is a collection of logger extras that makes structured logging setup easier.

Adding django-logger-extra your Django project

Add django-logger-extra in your project's dependencies.

Adding django-resilient-logger Django apps

To install this logger, add INSTALLED_APPS in settings.py:

INSTALLED_APPS = (
    "logger_extra",
    ...
)

Configuring logger formatter in settings.py:

To make use of the JSON formatter it must be configured in setting's LOGGING section. Filter is optional and brings logger_context() contexts available as logger extras.

LOGGING = {
    "filters": {
        "context": {
            "()": "logger_extra.filter.LoggerContextFilter",
        }
        ...
    },
    "formatters": {
        "json": {
            "()": "logger_extra.formatter.JSONFormatter",
        }
        ...
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "json",
            "filters": ["context"]
        },
        ...
    },
    ...
}

Configuring middleware in settings.py:

MIDDLEWARE = [
    "logger_extra.middleware.XRequestIdMiddleware",
    ...
]

django-auditlog extra context.

This library can also augment django-auditlog's additional_data fields with active context. To enable this, optional package django-auditlog must be installed and it must be explicitly enabled in settings.py file.

LOGGER_EXTRA_AUGMENT_DJANGO_AUDITLOG = True

In order to mask actor email on your django-auditlog log entries, you can set the following option in your settings.py file.

LOGGER_EXTRA_MASK_ACTOR_EMAIL = True

Logger context usage

Active context can be appended with logger_context function. It will return current context as resource. The current context can also be read using function get_logger_context.

import logging
from django.http import HttpRequest, JsonResponse

from logger_extra.logger_context import logger_context

logger = logging.getLogger("audit")

def bar():
  with logger_context({ "who": "World" }) as ctx:
    logger.info(f"{ctx['greet']} {ctx['who']}")

def foo():
  with logger_context({ "greet": "Hello" }):
    bar()
    return JsonResponse({})

Will result log entry that looks like: {"message": "Hello World", "level": "INFO", "time": "2025-04-14T11:08:22.962222+00:00", "context": {"request_id": "95e787b5-4ce8-46ef-bb6e-31651fc8774b", "greet": "Hello", "who": "World"}}

django-resilient-logger resolve_actor patch

This library also provides a utility actor resolver function for django-resilient-logger to guarantee that an actor's email (masked) and UUID is available in the resilient logger entries.

In order to activate the feature, add the following setting to your django-resilient-logger (version 3.1.0 or higher) configuration:

RESILIENT_LOGGER = {
    # ...
    "actor_resolver": "logger_extra.extras.resilient_logger.resolve_actor_with_masked_email",
}

Gunicorn Logging Formatters

This package includes two helpers to format Gunicorn access and error logs as structured JSON: JsonFormatter and JsonErrorFormatter (available at logger_extra.extras.gunicorn).

Use the following logconfig_dict in your Gunicorn configuration (default: gunicorn.conf.py) to enable JSON output and include the logger context filter so request context is available in logs:

from logger_extra.extras.gunicorn import JsonErrorFormatter, JsonFormatter

logconfig_dict = {
    "version": 1,
    "disable_existing_loggers": False,
    "filters": {
        "context": {
            "()": "logger_extra.filter.LoggerContextFilter",
        }
    },
    "formatters": {
        "json": {
            "()": JsonFormatter,
        },
        "json_error": {
            "()": JsonErrorFormatter,
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "json",
            "filters": ["context"],
            "stream": "ext://sys.stdout",
        },
        "error_console": {
            "class": "logging.StreamHandler",
            "formatter": "json_error",
            "filters": ["context"],
            "stream": "ext://sys.stderr",
        },
    },
    "root": {
        "handlers": ["console"],
        "level": "INFO",
    },
    "loggers": {
        "gunicorn.access": {
            "level": "INFO",
            "handlers": ["console"],
            "propagate": False,
        },
        "gunicorn.error": {
            "level": "INFO",
            "handlers": ["error_console"],
            "propagate": False,
        },
    },
}

Notes:

  • Access logs: JsonFormatter expects Gunicorn access log fields and will produce a JSON object containing time (in UTC), request/response metadata, and any active logger context.
  • Error logs: JsonErrorFormatter formats error messages with an ISO 8601 UTC timestamp and the log message. Also note that despite the name, all records logged in gunicorn.error are not errors, e.g. gunicorn's start-up messages are logged through this.
  • Context filter: Adding logger_extra.filter.LoggerContextFilter to the filters and attaching it to handlers ensures context created by logger_extra.logger_context is included under request_id and other context keys.
  • Gunicorn usage: If you're using a non-default name for your config file, point Gunicorn to your config file when starting, e.g. gunicorn -c my_gunicorn_conf.py myapp.wsgi:application.

Development

Virtual Python environment can be used. For example:

python3 -m venv .venv
source .venv/bin/activate

Install package requirements:

pip install -e .

Install development requirements:

pip install -r requirements-test.txt

Running tests

pytest

Code format

This project uses Ruff for code formatting and quality checking.

Basic ruff commands:

  • lint: ruff check
  • apply safe lint fixes: ruff check --fix
  • check formatting: ruff format --check
  • format: ruff format

pre-commit can be used to install and run all the formatting tools as git hooks automatically before a commit.

Git blame ignore refs

Project includes a .git-blame-ignore-revs file for ignoring certain commits from git blame. This can be useful for ignoring e.g. formatting commits, so that it is more clear from git blame where the actual code change came from. Configure your git to use it for this project with the following command:

git config blame.ignoreRevsFile .git-blame-ignore-revs

Commit message format

New commit messages must adhere to the Conventional Commits specification, and line length is limited to 72 characters.

When pre-commit is in use, commitlint checks new commit messages for the correct format.

Metadata

Release files for django-logger-extra 1.2.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 django-logger-extra 1.2.0
File Size Uploaded
django_logger_extra-1.2.0.tar.gz 18.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-logger-extra 1.2.0
File Interpreter ABI Platform
django_logger_extra-1.2.0-py2.py3-none-any.whl Python 3, Python 2 none any Details

Total release size: 30.1 kB

Release files / django_logger_extra-1.2.0.tar.gz

Download URL django_logger_extra-1.2.0.tar.gz
Size 18.2 kB
Tags Source
SHA-256 checksum
How to use checksums
f3a7158642252999733444e559a42128b0f17e6ee2c07f84fed9387764f3feed
BLAKE2b-256 checksum
How to use checksums
1339f631bb70c643d0ab3e907266807fdce1277dd1e4eb8b888135ea0220be1c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 9, 2026.

Transparency log

Release files / django_logger_extra-1.2.0-py2.py3-none-any.whl

Download URL django_logger_extra-1.2.0-py2.py3-none-any.whl
Size 11.9 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
07f75f06f37f59ecca7d0feac3370c22e9dbb1a09db52461a6e9da51f7dfafc8
BLAKE2b-256 checksum
How to use checksums
3e59b9ef9283847928261da0d36ba13402c980e60d9cfdf6721d09518f41b049
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 9, 2026.

Transparency log

Release history Release notifications | RSS feed

1.3.0

2 release files

This release

1.2.0 This release

2 release files

1.1.2

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.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