djangologgingdjango-settingsdjango-logging

Add custom log records in Django


I've added the following logging configuration to my Django App's settings.py file:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
        },
    },
}

Now, I simply want to add some custom log records to one of my views in views.py, but it appears the logger is NOTSET, which means only levels of warning and higher are logged:

import logging
from django.http import JsonResponse

logger = logging.getLogger(__name__)

def testing(request):
    logger.info("Doesn't show...")
    logger.warning(f"Log Level: {logger.level} = {logging.getLevelName(logger.level)}")
    return JsonResponse({"Hello": "World"})

The snippet above logs the following:

Log Level: 0 = NOTSET

Am I doing something wrong? Why is the logger's level not set (even though I clearly set it in settings.py)?


Solution

  • Why this behavior?

    The logging.getLogger(__name__) statement will initialize a python logger with a dotted path to the current module. In your case, it would be my_app.views. Django is not able to understand the logs that you have created from the views.py since your logger name my_app.views which is not listed in settings.py. Django won't do anything to the logs if you are not specified the logger name/ logger-name pattern accordingly.

    How warning logs are displayed?

    I hope this So post this explains well, Python logging not outputting anything

    Solution

    Option-1

    change either your logger name in settings.py

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
            },
        },
        'loggers': {
            'my_app.views': {
                'handlers': ['console'],
                'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
            },
        },
    }

    Key Change: I have changed the logger name django to my_app.views

    Option-2

    Specify logger name in the getLogger method

    logger = logging.getLogger('django')

    Key Point: The name of the logger and the logger defined in the Django Settings module should be same.