Skip to main content

Django middleware and log filter to attach a unique ID to every log message generated as part of a request

Project description

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

DEBUG [340d34bb4bb91ed4f45c414808a03a65] myproject.apps.myapp.views: Some log message
DEBUG [340d34bb4bb91ed4f45c414808a03a65] myproject.apps.myapp.forms: Some other log message

Installation and usage

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

Add the middleware to your MIDDLEWARE_CLASSES setting.

MIDDLEWARE_CLASSES = (
    'log_labeler.middleware.HeaderToLabelMiddleware',
    # ... other middleware goes here
)

Add the log_labeler.filters.HeaderToLabelFilter to your LOGGING setting. Update your formatters to include the header names you want appearing in the log message. Add a handler to output the messages (eg to the console), and finally attach the handler to your application's logger.

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"
]

LOG_LABEL_OBFUSCATE = {
    "headers": ["Authorization"],
    "body": {
        "(?i)(\\<(\\w+\\:)?password.*\\>).+(\\<\\/(\\w+\\:)?password.*\\>)": r"\1[--HIDDEN--]\3",
        "(?i)(\\<(\\w+\\:)?session.*\\>).+(\\<\\/(\\w+\\:)?session.*\\>)": r"\1[--HIDDEN--]\3",
        "(?i)(\\<(\\w+\\:)?token.*\\>).+(\\<\\/(\\w+\\:)?token.*\\>)": r"\1[--HIDDEN--]\3",
        "(?i)(.*\\??password([^=]*)=)([^\\&]*)(.*)": r"\1[--HIDDEN--]\4",
        "(?i)(.*\\??token([^=]*)=)([^\\&]*)(.*)": r"\1[--HIDDEN--]\4",
        "(?i)(.*\\??session([^=]*)=)([^\\&]*)(.*)": r"\1[--HIDDEN--]\4",
        "(?i)(.+\\\".*session.*\\\"\\s*\\:\\s*\\\")(.+)(\\\"(\\,|\\}).*)": r"\1[--HIDDEN--]\3",
        "(?i)(.+\\\".*token.*\\\"\\s*\\:\\s*\\\")(.+)(\\\"(\\,|\\}).*)": r"\1[--HIDDEN--]\3",
        "(?i)(.+\\\".*password.*\\\"\\s*\\:\\s*\\\")(.+)(\\\"(\\,|\\}).*)": r"\1[--HIDDEN--]\3",
    },
    "response": {
        "(?i)(\\<(\\w+\\:)?password.*\\>).+(\\<\\/(\\w+\\:)?password.*\\>)": r"\1[--HIDDEN--]\3",
        "(?i)(\\<(\\w+\\:)?session.*\\>).+(\\<\\/(\\w+\\:)?session.*\\>)": r"\1[--HIDDEN--]\3",
        "(?i)(\\<(\\w+\\:)?token.*\\>).+(\\<\\/(\\w+\\:)?token.*\\>)": r"\1[--HIDDEN--]\3",
        "(?i)(.*\\??password([^=]*)=)([^\\&]*)(.*)": r"\1[--HIDDEN--]\4",
        "(?i)(.*\\??token([^=]*)=)([^\\&]*)(.*)": r"\1[--HIDDEN--]\4",
        "(?i)(.*\\??session([^=]*)=)([^\\&]*)(.*)": r"\1[--HIDDEN--]\4",
        "(?i)(.+\\\".*session.*\\\"\\s*\\:\\s*\\\")(.+)(\\\"(\\,|\\}).*)": r"\1[--HIDDEN--]\3",
        "(?i)(.+\\\".*token.*\\\"\\s*\\:\\s*\\\")(.+)(\\\"(\\,|\\}).*)": r"\1[--HIDDEN--]\3",
        "(?i)(.+\\\".*password.*\\\"\\s*\\:\\s*\\\")(.+)(\\\"(\\,|\\}).*)": r"\1[--HIDDEN--]\3",
    },
    "url": {
        "(?i)(.*\\??password([^=]*)=)([^\\&]*)(.*)": r"\1[--HIDDEN--]\4",
        "(?i)(.*\\??token([^=]*)=)([^\\&]*)(.*)": r"\1[--HIDDEN--]\4",
        "(?i)(.*\\??session([^=]*)=)([^\\&]*)(.*)": r"\1[--HIDDEN--]\4",
    }
}

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 expected key headers, body, response and URL

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

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

django-log-labeler-1.0.3.tar.gz (11.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_log_labeler-1.0.3-py3-none-any.whl (14.4 kB view details)

Uploaded Python 3

File details

Details for the file django-log-labeler-1.0.3.tar.gz.

File metadata

  • Download URL: django-log-labeler-1.0.3.tar.gz
  • Upload date:
  • Size: 11.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/45.2.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.7.6

File hashes

Hashes for django-log-labeler-1.0.3.tar.gz
Algorithm Hash digest
SHA256 cc8dbbe206765eb02ff9401fb95706721c1cf7ea90e63b4169a83900a222bfd5
MD5 f7c68bde2ee294a6153ba9d817a111d8
BLAKE2b-256 dc644e1a39ae20411068b606a541e054b84921721cca9e2d6d24887fc7bbede9

See more details on using hashes here.

File details

Details for the file django_log_labeler-1.0.3-py3-none-any.whl.

File metadata

  • Download URL: django_log_labeler-1.0.3-py3-none-any.whl
  • Upload date:
  • Size: 14.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/45.2.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.7.6

File hashes

Hashes for django_log_labeler-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 36fde10e8bef64f23afb0e16408663a020953a35027145cda856b192605d5108
MD5 9143e4c531b476ed14747cb39b671e89
BLAKE2b-256 9b06067015eb7e917aa97057629f764f347a0ef6df469c6d60e1c46f6eaa895a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page