how-to logging Django   0   804
How to start logging errors in Django app

In development or testing environment, you may set DEBUG=True  in your  file and whenever any error is thrown, you see it in the browser.

Setting DEBUG=True  in production environment is not recommended. Debug should be set to False on live servers so that error trace is not visible in case of any error. Hackers or malicious users may exploit this and may attack your web application. So how do you debug you application on live servers?

Answer is Logging the errors in log files. Lets see how to start logging errors in Django?


Django uses python's built in logging module. Django's logging module consist four players.
  • Loggers
  • Handlers
  • Filters
  • Formatters

Logger is the entry point to any logging system. It is kind of a bucket with a name where you push your error message.

Handler decides what needs to be done for each message in logger.

Filters put restrictions on each message and decide which message should be passed from logger to handler. For example only messages with severity level equal to or higher than 'error' should be processed.

Formatters decide the format in which error messages should be displayed as text.

Log levels in python:

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.

Now lets see the coding version of the process. We will implement simplest version of logging.

How to Log errors in log files:

create a separate file for logging settings. Lets name it . Place this file along with settings file in project folder.

Put the below code in this file and save. We will explain later what each thing means in the code.

	'disable_existing_loggers': False,
			'format':'%(asctime)s  %(levelname)s  %(process)d  %(pathname)s  %(funcName)s  %(lineno)d  %(message)s  '
			'format':'%(asctime)s  %(message)s  '

Now import the  file in main  file. Add these lines in  file.

# importing logger settings
    from .logger_settings import *
except Exception as e:
    # in case of any error, pass silently.

In any view, throw an error and log it. Import logging and log the error in exception handling.

import logging

def index(request):
        raise Exception("Custom error thrown by newbie developer :D")
    except Exception as e:

Once you hit the url pointing to above view function, you will see an ErrorLogger<today's date>.log file will be created in current working project directory myproject/logs/  and error will be logged in it.

Understanding the code:

  • Django uses dictConfig format for logging configurations. Version defines the schema version to be used here. It accepts positive integer and as of now only acceptable valid value is 1 .
  • disable_existing_loggers if set to True disable any default loggers. This doesn't remove loggers from system but simply deactivate them and any such loggers simply discard any logging message received by them.
  • In the code above we defined two type of formatters, large and tiny. In large formatter we will be logging descriptive message with date time, log level, process, file name, function name, line number and error message. In tiny formatter we will be logging on message and date time.
  • We defined two type of handlers, error_file and info_file. error_file handler will handle messages with log level equal to or greater than error as defined by level key. logging.handlers.TimedRotatingFileHandler value in class field defines that files are created on time basis. When field have value midnight  which means new file is created at midnight. File name is the path to file. This path should have write permission. Formatter key define the formatter to use, large in this case.
  • We created two named loggers, error_logger and info_logger. We defined the log level and handler to use for each logger. If you do not want parent of any logger to capture and log the message then set propagation to false.

Example with code:

In one of our previous article, we developed a hello world django project.

Here we extended that project and uploaded on github.

Github url:  

For advance configuration:

Now host your Django app on server and access it anywhere. Test your application with real users.

how-to logging Django   0   804

Related Articles:
Python Script 3: Validate, format and Beautify JSON string Using Python
Validating json using python code, format and beautify json file using python, validate json file using python, how to validate, format and beautify json...
Encryption-Decryption in Python Django
How to encrypt and decrypt the content in DJango. Encrypting the critical information in Django App. Encrypting username, email and password in Django...
Adding Robots.txt file to Django Application
Adding robots.txt file in your Django application. Easiest way to add robots.txt file. Django application robots.txt file. Why should you add robots.txt file in your Django Application....
Scraping 10000 tweets in 60 seconds using celery, RabbitMQ and Docker cluster with rotating proxy
Scrapping large amount of tweets within minutes using celery, RabbitMQ and docker cluster. Scraping huge data quickly using docker cluster with TOR....

0 thoughts on 'How To Start Logging Errors In Django App'
Leave a comment:

*All Fields are mandatory. **Email Id will not be published publicly.

Please subscribe to get the latest articles in your mailbox.

Recent Posts:

© 2018-2019