A module that provides extras for logger.
Project description
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
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"}}
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:
JsonFormatterexpects Gunicorn access log fields and will produce a JSON object containing time (in UTC), request/response metadata, and any active logger context. - Error logs:
JsonErrorFormatterformats error messages with an ISO 8601 UTC timestamp and the log message. Also note that despite the name, all records logged ingunicorn.errorare not errors, e.g. gunicorn's start-up messages are logged through this. - Context filter: Adding
logger_extra.filter.LoggerContextFilterto thefiltersand attaching it to handlers ensures context created bylogger_extra.logger_contextis included underrequest_idand 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.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file django_logger_extra-1.1.2.tar.gz.
File metadata
- Download URL: django_logger_extra-1.1.2.tar.gz
- Upload date:
- Size: 15.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b86e2cbf5266997cceb7acb6b645b6916b9fc72cf466c71ef5b5eed672d5ed8b
|
|
| MD5 |
53e6624feaf0feb16a6176c79c07433a
|
|
| BLAKE2b-256 |
fa4a401ce9c4e3ef8a453f84b198bf6904f9959a7567cdca65d2bff76c9c4cde
|
Provenance
The following attestation bundles were made for django_logger_extra-1.1.2.tar.gz:
Publisher:
publish.yml on City-of-Helsinki/django-logger-extra
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
django_logger_extra-1.1.2.tar.gz -
Subject digest:
b86e2cbf5266997cceb7acb6b645b6916b9fc72cf466c71ef5b5eed672d5ed8b - Sigstore transparency entry: 1357015863
- Sigstore integration time:
-
Permalink:
City-of-Helsinki/django-logger-extra@dcf0bec20e280f68382a831ede03f7a9eb42be12 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/City-of-Helsinki
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@dcf0bec20e280f68382a831ede03f7a9eb42be12 -
Trigger Event:
push
-
Statement type:
File details
Details for the file django_logger_extra-1.1.2-py2.py3-none-any.whl.
File metadata
- Download URL: django_logger_extra-1.1.2-py2.py3-none-any.whl
- Upload date:
- Size: 10.2 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d71004c4956577e7bff2e3745d9432f55172a6cf29de3f11179e015469ab4d26
|
|
| MD5 |
657c6d2237a9f555057610793d68d7b2
|
|
| BLAKE2b-256 |
e53bb9339afaef62610f195ed5349b26a1c498cefcabfc2f58acde02a7ecec93
|
Provenance
The following attestation bundles were made for django_logger_extra-1.1.2-py2.py3-none-any.whl:
Publisher:
publish.yml on City-of-Helsinki/django-logger-extra
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
django_logger_extra-1.1.2-py2.py3-none-any.whl -
Subject digest:
d71004c4956577e7bff2e3745d9432f55172a6cf29de3f11179e015469ab4d26 - Sigstore transparency entry: 1357015865
- Sigstore integration time:
-
Permalink:
City-of-Helsinki/django-logger-extra@dcf0bec20e280f68382a831ede03f7a9eb42be12 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/City-of-Helsinki
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@dcf0bec20e280f68382a831ede03f7a9eb42be12 -
Trigger Event:
push
-
Statement type: