Search code examples
pythondjangologgingformatterdjango-logging

Add Dynamic custom variable in logging Formatter Django Python


Let the Following be the logging formatter in settings.py`

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %thread)d %(message)s'
        },
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': True,
        },
        'myproject.custom': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        }
    }
}

Now Say I have three files namely A.py, B.py & C.py

In A.py I have a decorator

def myDecorator():
    #Code to generate unique Id for each request in Django APP
    uniqueId = #something

In B.py & C.py i have many functions to handle various requests

import A.py import myDecorator
import logging

@myDecorator
def func1():
    #Some Code
    logger.debug("Logger message")

@myDecorator
def func2():
    #Some Code
    logger.info("Logger message")

@myDecorator
def func3():
    #Some Code
    logger.debug("Logger message")

def func4():
    #May be Some functions without logger too !!!!
    logger.debug("Logger message")

Now I want to log the generated unique Id along with the logger message without being passed explicitly every time in the logger & I also want to make it generic !

Is there by any way I can pass these unique ID's to loggers without passing it explicitly.

 'formatters': {
    'verbose': {
        'format': '%(levelname)s %(asctime)s %(module)s %(process)d 
            %thread)d %(message)s''%(unique_id)s'
    },
},

Whenever logger is trigger it should get its corresponding ID from the decorator & log it in %(unique_id)s or by default it should log None


Solution

  • The way this is typically done is by defining a custom Formatter and injecting your data, in your case the ID, into the log format by accessing the current request.