How Django Logging Works

July 2, 2021, 7:47 a.m.

In this tutorial , we are going to look at how logging works in Django. This is important and will make the process of troubleshooting easier.

Logging

Django uses Python’s logging module to perform system logging.

Advantages of Logging

  • It makes troubleshooting easier

  • We also get to know what is happening in our app

Terms

  • Loggers - loggers are named bucket where messages can be written.

  • Handlers - Handlers determine what will happen to message in a logger, for example, writing a message to the screen or to a file.

  • Filters - They help us control which log records will be passed from logger to handler.

  • Formatters - log record are rendered as text and formatters will describe the format of that text.

Naming loggers

  • Construction: logger = logging.getLogger(__name__)

  • The logger name is usually __name__ , the module’s name in Python. This makes it possible to filter and handle logging calls on a per-module basis.

A logger can be configured to have a log level. The log level will describe the severity of the messages that the logger is handling. Python defines the following log levels:

  • DEBUG: - Low level system information for debugging purposes.

  • INFO: - General system information.

  • WARNING: - Information describing a minor problem that has occurred.

  • ERROR: - Information describing a major problem that has occurred.

  • CRITICAL: - Information describing a critical problem that has occurred.

Example configuration

# settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            'format': '[{pathname}:{funcName}:{lineno:d}:{levelname}] {message}',
            'style': '{',
        },
        'file': {
            'format': '[{pathname}:{funcName}:{lineno:d}:{levelname}] {message}',
            'style': '{',
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'console'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'formatter': 'file',
            'filename': BASE_DIR + "/logfile.log",
        }
    },
    'root': {
        'level': 'DEBUG',
        'handlers': ['console', 'file']
    },
    'loggers': {
        'django.server': {
            'level': 'DEBUG',
            'handlers': ['console', 'file']
        }
    }
}

Note: The 'root' logger configuration goes outside the 'loggers' . The root Logger is the parent of all loggers.

Examples

# views.py

logger = logging.getLogger(__name__)

def home(request):

    logger.error("Something went wrong !!")

    return HttpResponse("Just testing if logging works")


def log_server_error(request):

    return HttpResponseServerError("log internal server error ")

  • Every time the user lands on the home view, an error log record will be written.

  • The second view is named log_server_error, it acts just like HttpResponse but uses a 500 status code. 'django.server' logger will log any occurrence of 500 Internal Server Error (logs only in development server).

Get Source Code on Github : Django-logging-example

Resources

Logging

Header photo by Jess Bailey on unsplash

Keep Learning