Skip to main content

django-log-labeler

Django middleware and log filter to attach values from the headers to every log message generated as part of a request.

Author: Hermann Stephane Ntsamo

Example

{"message": "Hello World", "correlation_id": "6da1d73a-9a72-4206-93a4-bac892b76784", "session_id": "none", "app_id": "none", "nim_user": "none", "app_version": "none"}

Installation and usage

First, install the package: pip install django-log-labeler

Add the middleware to your MIDDLEWARE_CLASSES setting.

INSTALLED_APPS = [
    ...
    'log_labeler',
    'pythonjsonlogger'
]
MIDDLEWARE_CLASSES = (
    'log_labeler.middleware.HeaderToLabelMiddleware',
    # ... other middleware goes here
)

An example LOGGING setting is below:

DEFAULT_LOG_LEVEL = os.getenv('LOGGING_LEVEL', 'INFO')

LOG_LABEL_REQUEST_SETTING = {
    "correlation_id": "HTTP_NIM_CORRELATION_ID",
    "session_id": "HTTP_NIM_SESSION_ID",
    "app_id": "HTTP_NIM_APP_ID",
    "nim_user": "HTTP_NIM_USER",
    "app_version": "HTTP_NIM_APP_VERSION",
}

LOG_LABEL_EXCLUDE_LOG_LIST = [
    "",
    "django"
]

#Case Insensitive
LOG_LABEL_OBFUSCATE = {
    "headers": ["Authorization"],
    "body": [
        ("PasswordText", Obfuscation_Type.XML),
        ("sessionID", Obfuscation_Type.XML),
        ("password", Obfuscation_Type.JSON),
        ("token", Obfuscation_Type.JSON)
    ],
    "response": [
        ("sessionID", Obfuscation_Type.XML),
        ("password", Obfuscation_Type.JSON),
        ("token", Obfuscation_Type.JSON),
        ("sessionid", Obfuscation_Type.JSON,)
    ],
    "url": [
        ("token", Obfuscation_Type.URL),
    ]
}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'request_id': {
            '()': 'log_labeler.filters.HeaderToLabelFilter'
        }
    },
    'formatters': {
        'json': {
              '()': 'pythonjsonlogger.jsonlogger.JsonFormatter',
              'format': '%(message)s'
          }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'filters': ['request_id'],
            'formatter': 'json',
        },
    },
    'loggers': {
        'log_labeler.middleware': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'gunicorn.access': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
    }
}

NIM_DJANGO_REQUEST_LOG_LEVEL_NAME = "HTTP_NIM_DJANGO_REQUEST_LOG_LEVEL"
MAX_REQUEST_RESPONSE_SIZE = os.getenv('MAX_REQUEST_RESPONSE_SIZE', 'OFF')

You can then output log messages as usual:

import logging
logger = logging.getLogger(__name__)
logger.debug("Hello world!")

Settings Description:

######DEFAULT_LOG_LEVEL The default log level to apply on the logger if not other log level is specified

######LOG_LABEL_REQUEST_SETTING The list of key/value pair that maps an HTTP header to a log entry

######LOG_LABEL_EXCLUDE_LOG_LIST The list of loggers to ignore when dynamically changing log levels

######LOG_LABEL_OBFUSCATE The dictionary with obfuscation rules

######NIM_DJANGO_REQUEST_LOG_LEVEL_NAME The name of the header to use to change the logging level. EG: DEBUG, INFO, ERROR...

######MAX_REQUEST_RESPONSE_SIZE The maximum allowed size for request and responses in case they are successful. Error message are not truncated.

License

Copyright © 2012-2018, DabApps.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Metadata

Release files for django-log-labeler 1.2.5

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-log-labeler 1.2.5
File Size Uploaded
django-log-labeler-1.2.5.tar.gz 13.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-log-labeler 1.2.5
File Interpreter ABI Platform
django_log_labeler-1.2.5-py2-none-any.whl Python 2 none any Details

Total release size: 30.8 kB

Release files / django-log-labeler-1.2.5.tar.gz

Download URL django-log-labeler-1.2.5.tar.gz
Size 13.7 kB
Tags Source
SHA-256 checksum
How to use checksums
440e167cbe9bc19603d22e0fd08d18c24e81be1079370815fb28d0d765ad36ec
BLAKE2b-256 checksum
How to use checksums
b643261a05395ab63a82269dc806acac324439540640c937adfb791209759d19
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/42.0.2 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/3.7.6

Release files / django_log_labeler-1.2.5-py2-none-any.whl

Download URL django_log_labeler-1.2.5-py2-none-any.whl
Size 17.1 kB
Tags Python 2
SHA-256 checksum
How to use checksums
800799a03225f190c245e534590040f0ac652153a3311532e94b29bc0fb84720
BLAKE2b-256 checksum
How to use checksums
bbab9c70d6508f6d52442bcf3d7d5c2135c10a4f77fd884f291df7b4484a7295
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/42.0.2 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/3.7.6

Release history Release notifications | RSS feed

This release

1.2.5 This release

2 release files

1.2.4

3 release files

1.2.2

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.9

2 release files

1.0.8

1 release file

1.0.7

2 release files

1.0.6

2 release files

1.0.5

2 release files

1.0.4

2 release files

1.0.3

2 release files

1.0.2

2 release files

1.0.0

2 release files

0.0.46

2 release files

0.0.45

2 release files

0.0.44

2 release files

0.0.43

2 release files

0.0.42

2 release files

0.0.27

2 release files

0.0.26

2 release files

0.0.25

2 release files

0.0.24

2 release files

0.0.23

2 release files

0.0.22

2 release files

0.0.21

2 release files

0.0.20

2 release files

0.0.19

2 release files

0.0.18

2 release files

0.0.17

2 release files

0.0.16

2 release files

0.0.15

2 release files

0.0.14

2 release files

0.0.13

2 release files

0.0.12

2 release files

0.0.11

2 release files

0.0.10

2 release files

0.0.9

2 release files

0.0.8

2 release files

0.0.7

2 release files

0.0.6

1 release file

0.0.5

1 release file

0.0.3

1 release file

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