Django Logging – A Quick Set-Up Guide

Django LOGGING

In this article we will learn all about logging in Django logging!!

Why does logging matter?

Being a programmer, we write lots of code and hence will also end up having lots of errors. Now it is very time-consuming to traceback and find where exactly the error is.

This is where the logging Module comes into rescue. Logging kind of gives a new vision to the developers to find and debug the error quickly.

What is logging in Django?

Logging is a technique that enables you to trace events occurring as the code/system is running in real-time.

Logging works as a separate program. You can think of it as a simple file-writer. When the system runs, it tracks events and records it down into the console or into files called logs.

The logs are simple files with a log extension having all the records in text format. Also, logging has further additional features like:

  • Makes multi-threading execution possible
  • Option to categorize messages via different log levels
  • Much more flexible and configurable.
  • Has a more structured information

4 Part of a Django logging

There are 4 parts of performing Django logging. Let’s find out what they are.

1. Django Logger

This is an entry to the logging system. The logger is a part which, when logging is called, records the event for processing. Also, a logger is configured to have a log level.

A log-level states the severity of the event that the logger will take in or handle.

Log-LevelDescriptionSeverity
DEBUGSystem information when everything is running fine.10
INFOSimilar to debug. It generally tells an overview of what the system is executing.20
WARNINGInvolves low-level problems that don’t cause the system to stop.30
ERRORThis message is serious. This shows the problem may have stopped the operation of the system and needs immediate attention40
CRITICALMost critical message. This is shown when the problem caused the system to stop.50

Each message that is written into the logger is called a Log record. Only those messages whose Log-level is greater that the logger is taken in for processing and rest all ignored.

2. Django Handler

This is the next level in the Django logging system. This has further information about what happens to the log records in the logger. That is, it has information about the location(console or a file, etc), the log record will be written, the type of filter and formatter to be applied to the log record.

Like loggers, Handlers also have log-level. If a log record does not have a log level equal or above the Handler’s log level, then it will be ignored.

3. Django Filter

As the name suggests it provides further filtering to the Log records, passed from the logger to handler. For example, Normally a log message that meets the log-level requirements will be handled. But you could install a filter that allows only the ERROR messages from a particular source to be emitted/written.

4. Django Formatters

Ultimately a log record has to be stored as a text. The log records are usually in the log record format predefined by the logging framework. But to store it a file, we need to convert it first into the correct format.

Hence formatters are used to convert them. Formatters by default convert it into strings. But can be changed and customized according to our needs as well.


The flow is very simple.

Logging Flow
Logging Flow

Add the Django Logging Directory to the settings.py

All the information about loggers, handlers, filters and formatters has to be written in settings.py itself.

The basic syntax is:

LOGGING = {
    'version': 1,
    # Version of logging
    'disable_existing_loggers': False,

    'filters':{
        #information regarding filters
    },

    'formatters':{
        '<formatter_name>':{
            'format': '<formatter_info>',
            'style': '{',
        }
    },

    'handlers': {
        'file': {
            'level': '<log_level>',
            'class': '<logging_class>',
            'filename': '<file_name>',
        },

        'console': {
            'class': '<logging_class>',
        },
    },

    'loggers': {
        'django': {
            'handlers': ['file', 'console'],
            'level': '<log_level>',
        },
    },

Here:

  • version: It’s the version of the logging we are using.
  • disable_existing_loggers: As a default, Django has the loggers disabled. So we need to enable them back.
  • Filters: Mentions the filters that we will use in logging.
  • Formatters: All information regarding the format of Log records has present here.
  • Handlers: All the process that has to be carried upon the log records are written here. Like the location of storage, formatters to be used, filters to be added, etc.
  • Loggers: This has the information of the handler; the log record will be passed on to, the log level, etc.

Therefore let’s add a simple Logging directory in our application that will save all the records with log level more than or equal to DEBUG into a log file present in the log folder.

Create a log folder in the Django project folder

logs
logs

In settings.py add the code:

LOGGING
LOGGING

Just remember the logic we learned in the above section and try to understand the code!

Call the Django Logging Function in views.py

Now that we have specified the logging in settings.py, we have to add function calls wherever we want in the views.py file in views.py import logging and then write the code at the beginning

import logging
logger = logging.getLogger(__name__)

__name__ pulls the name of the file that the function is called in. You an use this to identify the current file and add the logging methods from there on.

I have added logging.info function call at random places in views.py file for demonstration

Views 1
Views 1

Similarly in the ItemView:

Views 2
Views 2

Run Django Logging

That’s it fellas!! We can now run the program and let logging take care of all the log records.

python manage.py runserver

After this, log_file1.log will get automatically created and start storing the log records.

Log File
Log File

The log is stored with the level name first and then the message, just as we mentioned in the formatter.

Conclusion

That’s it, guys !!  This is all about Django Logging. Do check out the Python Logging for more information regarding Logging. Also, you can know more about Django logging from the official documentation. Stay safe !! keep learning !!