Django - Configure logging settings

Apr 29, 2017 Djnago 中文版

Django is a popular web framework written in Python, and it provides an elegant mechanism for logging. But it might be a little bit complicated if you’re new to Django. Thus, this post is about how to configure logging settings for you application.



Prerequisite

If you have not created a proper environment for the following steps, you can use below commands:

# Install Django
python -m pip install Django

# Check Django's version
python -m django --version

# Create a new Django project
django-admin startproject <project-name>

The structure of your project should look like this:

project-name/
├── project-name
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py


Understand logging settings

Before we dive into logging, get some basic information. When using the command django-admin startproject to create a project, logging settings won’t be automatically added. So, we have to manually add it into settings.py. Here is a simple example:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        # TODO
    },
    'handlers': {
        # TODO
    },
    'loggers': {
        # TODO
    },
    'filters': {
        # TODO
    },
}

As a beginner, let’s just focus on formatters, handlers and loggers for now.

  • formatters : it describes the format of your logging messages.
  • handlers : it specifies how do you want to handle logging messages, such as writing them to text files or outputting to console.
  • loggers : it defines log level and which handlers you want to use.

Below is a picture describing their relationships:

Set formatters

Ok, let’s continue to complete each part. In formatters, we need specify formats like below:

    'formatters': {
        'your-formatter': {
            '()': 'django.utils.log.ServerFormatter',
            'format': '[%(asctime)s] %(message)s',
        }
    },

As you see, I defined a simple string format ( [%(asctime)s] %(message)s ) :

  • %(asctime)s : Human-readable time format. For example: 2003-07-08 16:49:45,896
  • %(message)s : Texts of your logging message

The output would look like this:

[2017-04-26 11:07:33,380] Your message is here

Of course, there are more options we can use. Check here.

Set handlers

Here is an example for setting handlers:

    'handlers': {
        'web': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/your-web.log',
            'formatter': 'your-formatter'
        },
        'other_service': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/path/to/your-other-service.log',
            'formatter': 'your-formatter'
        },
    },

I defined two handlers for different tasks, and these handlers will create two different log files in different places.

  • level : it describes the log level.
  • class : it specifies the name of a handler class. In the example, we use logging.FileHandler for writing text files.
  • filename : it defines the name of your log file and where you want to store it.
  • formatter : it describes which formatter you want to use.

Visit here to get more details.

Set loggers

An example for setting loggers:

    'loggers': {
        'your-logger': {
            'handlers': ['web'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
  • handlers : it describes which handlers you want to use.
  • level : it describes the log level.

I’m not going to talk about propagate here because it needs more time to elaborate. But you can have a basic understanding of it by reading this.

Using logging

After we finished setting up logging, it’s time to use it in your Python scripts:

# Use logging library
import logging

# Get an instance of a logger
logger = logging.getLogger('your-logger')

# Log a message
logger.info('Your message is here.')




You might also like:




If you have any suggestions, questions or even find some typos, feel free to contact me. Thank you! :)

zeckli.devforgalaxy@gmail.com   © 2015-2019 zeckli, thanks to Jekyll and GitHub.