Python

How To Use Django Logging?

Every programmer faces errors when writing code for developing any application. The debugging is used by the coder to solve the errors of the application. Its logging feature makes the debugging process easier by saving the output of error, warning, and information messages into a file. These messages help the coders to keep track of the events, understand the reason for the unwanted output, and modify the code properly for creating an error-free application. Python has a built-in logging module to perform logging-related tasks more efficiently. Django is a popular python framework that uses the python built-in logging module for debugging purposes. How the python logging module can be used in the Django application for debugging purposes will be explained in this tutorial.

Different parts of Django Logging

Django logging contains four types of configurations which are explained below.

1. Django Logger
The logger records the events when the application is executed, and the logging is called. The log entries are stored in a file by categorizing them in different log levels. Every log level indicates the severity of the events. The purposes of these log levels are mentioned below:

  1. DEBUG
    It provides low-level system information for debugging.
  1. INFO
    It provides general information.
  1. ERROR
    It provides information about the major problem of the application.
  1. WARNING
    It provides information about the minor problem of the application.
  1. CRITICAL
    It provides information about the critical problem of the application.

2. Django Handler
The main task of the handler is to transmit the log information that is stored in the log file. The logging module contains many types of handlers and multiple of them can be defined for the same logger.

3. Django Formatter
It is used to format the log data. The data of the handler cannot be sent directly to the log file and the handler data requires it to be converted by using the formatter before sending. The formatter converts the log records into the string. The format of the data depends on the business logic of the handler.

4. Django Filter
It is used to filter the log messages. It is unnecessary to store all log messages into the log file. Different handlers can be used for different messages and the required log messages can be filtered using the required filters.

Prerequisites

Before practicing the script of this tutorial, you must complete the following tasks:

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not.

Setup a Django app

  1. Run the following command to create a Django app named logapp.
$ python3 manage.py startapp logapp
  1. Run the following command to create the user for accessing the Django database. If you have created the user before then don’t need to run the command.
$ python3 manage.py createsuperuser
  1. Add the app name in the INSTALLED_APP part of the py file.
INSTALLED_APPS = [
    …..
    'logapp'
]

Set the Logging Information in settings.py

Open the settings.py file from the Django project folder and add the following content to define the logging information. The properties of the handlers and loggers are set here. According to the logging property values, DEBUG level logging information will be stored in a log file named djangoapp.log when the Django app will be executed.

# Django Logging Information
LOGGING = {
    # Define the logging version
    'version': 1,
    # Enable the existing loggers
    'disable_existing_loggers': False,

    # Define the handlers
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'djangoapp.log',
        },

        'console': {
            'class': 'logging.StreamHandler',
        },
    },

   # Define the loggers
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,

        },
    },
}

Open the djangoapp.log file to check log entries are stored in the file or not.

Set the Logging Information in views.py

Logging information can be defined using the view file also. Open the views.py file from the logapp folder and replace the content with the following script. In this script, formatters, handlers, and loggers parts of Django logging are defined in the config.dictConfig() method. DEBUG level logging information will be stored in a log file named djangoapp.log and will be printed in the console when the Django app will be executed. index() function is used to send a simple headline text to the browser and the display_log() function is defined to send a simple text in the terminal and a headline text to the browser.

views.py

# Import the logging module
import logging
# Import HttpResponse to send data to the browser
from django.http import HttpResponse

# Define the logging configurations
logging.config.dictConfig({
   # Define the logging version
    'version': 1,
    # Enable the existing loggers
    'disable_existing_loggers': False,
   
   # Define the formatters
    'formatters': {
        'console': {
            'format': '%(message)s'
        },
        'file': {
            'format': '%(message)s'
        },
   
   # Define the handlers
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'console'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'formatter': 'file',
            'filename': 'djangoapp.log'
        }
    },
   
   # Define the loggers
    'loggers': {
        'django': {
            'level': 'DEBUG',
            'handlers': ['file', 'console'],

        }
    }
}

})

# Create the loggers object
logger = logging.getLogger('__name__')

# Define the  function for the index page
def index(request):
    return HttpResponse("<h1 style='color:blue'>This is a Django Application</h1>")

# Define the  function for the log page
def display_log(request):
    # Send the Test!! log message to standard out
    logger.error("Testing Django log...")
    return HttpResponse("<h1 style='color:Red'>Django Logging Message</h1>")

Modify the content of the urls.py file with the following script. In the script, the empty path(”) path is defined to call the index() function of the views and the ‘log/’ path is used to call the display_log() function of the views.

urls.py

from django.urls import path
from logapp import views

urlpatterns = [
    path('', views.index),
    path('log/', views.display_log)
]

Run the following URL to display the index page.

http://localhost:8000

Run the following URL to call the display_log() method that will display a text message in the browser and a text message in the terminal. Log entries will be appended in the djangoapp.log file.

Conclusion

Two ways of using python logging in the Django application to keep the DEBUG level logging information are shown in this tutorial. The basic concept regarding Django logging is expected to be understood by the readers after reading this tutorial.

About the author

Kevin Reursora