Django Google Structured Logger
Django Google Structured Logger is a Django middleware designed to capture and log details from incoming requests and outgoing responses. It offers features to mask sensitive data, set default fields for Google Cloud Logging, and structure logs in a detailed and organized manner.
Contents
Features:
- Detailed Logging: Logs both requests and responses with meticulous details.
- Sensitive Data Masking: Masks sensitive information using customizable regex patterns.
- Google Cloud Logging Support: Formats logs to match Google Cloud Logging standards.
- Configurable Settings: Customize log behavior through Django settings.
Usage:
Installation
You can install the package using pip:
pip install django-google-structured-logger
Configuration
-
Add
GoogleFormatterto your Django'sLOGGINGsetting. Example:LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "json": { "()": "django_google_structured_logger.formatter.GoogleFormatter", }, }, "handlers": { "console": { "level": "INFO", "class": "logging.StreamHandler", }, "google-json-handler": { "class": "logging.StreamHandler", "formatter": "json", }, }, "root": { "handlers": [env.str("DJANGO_LOG_HANDLER", "google-json-handler")], "level": env.str("ROOT_LOG_LEVEL", "INFO"), }, "loggers": { "()": { "handlers": [env.str("DJANGO_LOG_HANDLER", "google-json-handler")], "level": env.str("DJANGO_LOG_LEVEL", "INFO"), }, "django": { "handlers": [env.str("DJANGO_LOG_HANDLER", "google-json-handler")], "level": env.str("DJANGO_LOG_LEVEL", "INFO"), "propagate": False, }, "django.server": { "handlers": [env.str("DJANGO_LOG_HANDLER", "google-json-handler")], "level": env.str("DJANGO_SERVER_LEVEL", "ERROR"), "propagate": False, }, "django.request": { "handlers": [env.str("DJANGO_LOG_HANDLER", "google-json-handler")], "level": env.str("DJANGO_REQUEST_LEVEL", "ERROR"), "propagate": False, }, }, }
-
Add
SetRequestToLoggerMiddlewareto your Django'sMIDDLEWAREsetting.Django middleware:
MIDDLEWARE = [ ... # Ordering is important: "django_google_structured_logger.middlewares.SetUserContextMiddleware", # Set user context to logger. "django_google_structured_logger.middlewares.LogRequestAndResponseMiddleware", # Log request and response. ]
GRAPHENE middleware:
GRAPHENE = { "MIDDLEWARE": [ ... "django_google_structured_logger.graphene_middlewares.GrapheneSetUserContextMiddleware", # Set user context to logger. ] }
-
Ensure your Django project has the necessary configurations in the
settings.py.
Key Components:
1. middleware.py
- SetRequestToLoggerMiddleware: This class contains methods to process incoming requests and outgoing responses and then log them. It supports features like abridging lengthy data and masking sensitive information.
2. formatter.py
- GoogleFormatter: Extends
jsonlogger.JsonFormatterto format logs specifically for Google Cloud Logging. It sets default fields such as severity, labels, operation, and source location based on Google's logging standards.
3. settings.py
- Provides a list of default sensitive keys for data masking.
- Allows customization of logging behavior with options to specify maximum string length, excluded endpoints, sensitive keys, and more.
Settings:
These are the settings that can be customized for the middleware:
LOG_MAX_STR_LEN: Maximum string length before data is abridged. Default is200.LOG_MAX_LIST_LEN: Maximum list length before data is abridged. Default is10.LOG_EXCLUDED_ENDPOINTS: List of endpoints to exclude from logging. Default is anempty list.LOG_SENSITIVE_KEYS: Regex patterns for keys which contain sensitive data. DefaultsDEFAULT_SENSITIVE_KEYS.LOG_MASK_STYLE: Style for masking sensitive data. Default is"partially".LOG_MIDDLEWARE_ENABLED: Enable or disable the logging middleware. Default isTrue.LOG_EXCLUDED_HEADERS: List of request headers to exclude from logging. DefaultsDEFAULT_SENSITIVE_HEADERS.LOG_USER_ID_FIELD: Field name for user ID. Default is"id".LOG_USER_DISPLAY_FIELD: Field name for user email. Default is"email".LOG_MAX_DEPTH: Maximum depth for data to be logged. Default is4.
Note:
- All settings are imported from
django_google_structured_logger.constants.
Other Notes:
extrakwargs passed to logger, for example:logger.info("some message", extra={"some_key": "some_data}
will be logged as structured data in thejsonPayloadfield in Google Cloud Logging. Any data passed to extra kwargs will not be abridged or masked.extrakwargs passed to logger may override any default fields set byGoogleFormatter.
Conclusion:
SetRequestToLoggerMiddleware is a comprehensive solution for those seeking enhanced logging capabilities in their Django projects, with particular attention to sensitive data protection and compatibility with Google Cloud Logging.
To get started, integrate the provided middleware, formatter, and settings into your Django project, customize as needed, and enjoy advanced logging capabilities!
Metadata
Release files for django-google-structured-logger 2.8.11
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| django_google_structured_logger-2.8.11.tar.gz | 31.1 kB | Without provenance | Details for django_google_structured_logger-2.8.11.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| django_google_structured_logger-2.8.11-py3-none-any.whl | Python 3 | none | any | Details for django_google_structured_logger-2.8.11-py3-none-any.whl |
Total release size: 43.2 kB
Release files / django_google_structured_logger-2.8.11.tar.gz
| Download URL | django_google_structured_logger-2.8.11.tar.gz |
|---|---|
| Size | 31.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
543ffb4921bd6ec576ff9878a5dfd326fceb092dd97c8e003f9473780f6378e8
|
|
BLAKE2b-256 checksum How to use checksums |
a7b397807e817e3b183e60dadac1c8ad6c78e9fdb4e08b1c5cc2781c19da43fc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Release files / django_google_structured_logger-2.8.11-py3-none-any.whl
| Download URL | django_google_structured_logger-2.8.11-py3-none-any.whl |
|---|---|
| Size | 12.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
05004abf332913a0e7bc013150008a9e89f01337d6af84d7476388c2675803ba
|
|
BLAKE2b-256 checksum How to use checksums |
6e07f7d813b40a3ed42d237cbc9aef4bd0aebcef334fc1844b762bf63b132331
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Security for django-google-structured-logger 2.8.11
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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.