-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
MP-432 Create Django library for Google Structured Logger (GSL)
- Loading branch information
0 parents
commit 97cf553
Showing
16 changed files
with
1,147 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
name: Release | ||
|
||
on: | ||
push: | ||
tags: | ||
- '*' | ||
|
||
jobs: | ||
build: | ||
if: github.repository == 'muehlemann-popp/django-google-structured-logger' | ||
runs-on: ubuntu-latest | ||
|
||
steps: | ||
- uses: actions/checkout@v3 | ||
with: | ||
fetch-depth: 0 | ||
|
||
- name: Set up Python | ||
uses: actions/setup-python@v4 | ||
with: | ||
python-version: 3.9 | ||
|
||
- name: Install dependencies | ||
run: | | ||
python -m pip install -U pip | ||
python -m pip install -U setuptools twine wheel | ||
- name: Build package | ||
run: | | ||
python setup.py --version | ||
python setup.py sdist --format=gztar bdist_wheel | ||
twine check dist/* | ||
- name: Publish package | ||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags') | ||
uses: pypa/gh-action-pypi-publish@release/v1 | ||
with: | ||
password: ${{ secrets.PYPI_API_TOKEN }} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
/*.egg-info | ||
.eggs | ||
/__pycache__ | ||
.pytest_cache | ||
*.pyc | ||
/reports | ||
/.coverage | ||
/build | ||
.idea | ||
dist |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
exclude: docs|node_modules|migrations|.tox | ||
default_stages: [commit] | ||
fail_fast: true | ||
|
||
repos: | ||
- repo: https://github.com/pre-commit/pre-commit-hooks | ||
rev: v4.4.0 | ||
hooks: | ||
- id: trailing-whitespace | ||
exclude: static | ||
- id: end-of-file-fixer | ||
exclude: static | ||
- id: pretty-format-json | ||
args: [--autofix] | ||
|
||
- repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks | ||
rev: v2.10.0 | ||
hooks: | ||
- id: pretty-format-yaml | ||
args: [--autofix, --indent, '2'] | ||
|
||
- repo: https://github.com/timothycrosley/isort | ||
rev: 5.12.0 | ||
hooks: | ||
- id: isort | ||
|
||
- repo: https://github.com/psf/black | ||
rev: 23.9.1 | ||
hooks: | ||
- id: black | ||
|
||
- repo: https://github.com/pycqa/flake8 | ||
rev: 6.1.0 | ||
hooks: | ||
- id: flake8 | ||
additional_dependencies: [flake8-isort] | ||
|
||
- repo: https://github.com/pre-commit/mirrors-mypy | ||
rev: v1.5.1 | ||
hooks: | ||
- id: mypy | ||
args: [--install-types, --non-interactive] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
Copyright 2021 Mühlemann & Popp Online Media AG | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
include README.md | ||
include LICENSE | ||
recursive-include docs * | ||
|
||
recursive-exclude * __pycache__ | ||
recursive-exclude * *.py[co] | ||
recursive-exclude * *.orig |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
## 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](#features) | ||
* [Usage](#usage) | ||
* [Key Components](#key-components) | ||
* [Settings](#settings) | ||
* [Conclusion](#conclusion) | ||
|
||
### Features: | ||
|
||
1. **Detailed Logging**: Logs both requests and responses with meticulous details. | ||
2. **Sensitive Data Masking**: Masks sensitive information using customizable regex patterns. | ||
3. **Google Cloud Logging Support**: Formats logs to match Google Cloud Logging standards. | ||
4. **Configurable Settings**: Customize log behavior through Django settings. | ||
|
||
### Usage: | ||
|
||
1. Add `GoogleFormatter` to your Django's `LOGGING` setting. | ||
Example: | ||
```python | ||
LOGGING = { | ||
"version": 1, | ||
"disable_existing_loggers": False, | ||
"formatters": { | ||
"json": { | ||
"()": "django_google_structured_logger.formatter.GoogleFormatter", | ||
}, | ||
}, | ||
"handlers": { | ||
"google-json-handler": { | ||
"class": "logging.StreamHandler", | ||
"formatter": "json", | ||
}, | ||
}, | ||
"root": { | ||
"handlers": ["google-json-handler"], | ||
"level": logging.INFO, | ||
} | ||
} | ||
``` | ||
2. Add `SetRequestToLoggerMiddleware` to your Django's `MIDDLEWARE` setting. | ||
Example: | ||
```python | ||
MIDDLEWARE = [ | ||
... | ||
"django_google_structured_logger.middleware.SetRequestToLoggerMiddleware", | ||
] | ||
``` | ||
3. 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.JsonFormatter` to 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 is 200. | ||
- **LOG_MAX_LIST_LEN**: Maximum list length before data is abridged. Default is 10. | ||
- **LOG_EXCLUDED_ENDPOINTS**: List of endpoints to exclude from logging. Default is an empty list. | ||
- **LOG_SENSITIVE_KEYS**: Regex patterns for keys which contain sensitive data. Defaults provided. | ||
- **LOG_MASK_STYLE**: Style for masking sensitive data. Default is "partially". | ||
- **LOG_MASK_CUSTOM_STYLE**: Custom style for masking if `LOG_MASK_STYLE` is set to "custom". Default is just the data itself. | ||
- **LOG_MIDDLEWARE_ENABLED**: Enable or disable the logging middleware. Default is True. | ||
- **LOG_EXCLUDED_HEADERS**: List of request headers to exclude from logging. Default is ["Authorization"]. | ||
- **LOG_USER_ID_FIELD**: Field name for user ID. Default is "id". | ||
- **LOG_USER_EMAIL_FIELD**: Field name for user email. Default is "email". | ||
|
||
### 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! |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from django.apps import AppConfig # type: ignore | ||
|
||
|
||
class DjangoMaterializedViewAppConfig(AppConfig): | ||
default_auto_field = "django.db.models.BigAutoField" | ||
name = "django_google_structured_logger" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
from pythonjsonlogger import jsonlogger # type: ignore | ||
|
||
from .storages import RequestStorage, get_current_request | ||
|
||
|
||
class GoogleFormatter(jsonlogger.JsonFormatter): | ||
google_source_location_field = "logging.googleapis.com/sourceLocation" | ||
google_operation_field = "logging.googleapis.com/operation" | ||
google_labels_field = "logging.googleapis.com/labels" | ||
|
||
def add_fields(self, log_record: dict, record, message_dict: dict): | ||
"""Set Google default fields | ||
List of Google supported fields: | ||
https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry | ||
List of associated JSON fields: | ||
https://cloud.google.com/logging/docs/structured-logging#default-parsers | ||
This method sets these fields if present: | ||
- severity | ||
- labels | ||
- operation | ||
- sourceLocation | ||
""" | ||
super().add_fields(log_record, record, message_dict) | ||
current_request: RequestStorage | None = get_current_request() | ||
|
||
log_record["severity"] = record.levelname | ||
|
||
log_record[self.google_labels_field] = { | ||
"request_user_id": current_request.user_id() if current_request else None, | ||
"request_user_email": current_request.user_email() | ||
if current_request | ||
else None, | ||
**log_record.pop(self.google_labels_field, {}), | ||
**log_record.pop("labels", {}), | ||
} | ||
self.stringify_values(log_record[self.google_labels_field]) | ||
|
||
log_record[self.google_operation_field] = { | ||
"id": current_request.uuid if current_request else None, | ||
"last": log_record.get("last_operation", False), | ||
**log_record.pop(self.google_operation_field, {}), | ||
**log_record.pop("operation", {}), | ||
} | ||
log_record[self.google_source_location_field] = { | ||
"file": record.pathname, | ||
"line": record.lineno, | ||
"function": record.funcName, | ||
"logger": record.name, | ||
} | ||
|
||
@staticmethod | ||
def stringify_values(dict_to_convert: dict): | ||
for key in dict_to_convert: | ||
dict_to_convert[key] = str(dict_to_convert[key]) |
Oops, something went wrong.