[Django] A brief summary of the log output function so that even beginners can understand it.

Introduction

Django's Logging feature can be difficult to understand at first glance. Especially the configuration file. I will summarize it easily and concisely.

Production environment assumption configuration file

It's a log setting, but if you don't set it yourself (if there is no LOGGING definition in settings.py) [Default settings included in the Django source](https://github.com/django/django/ blob / master / django / utils / log.py) will be used. However, the output log is not very easy to see, so in most cases you set it yourself. The following is a setting example assuming a production environment. Add the following contents to settings.py.

settings.py


LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    #Log output format settings
    'formatters': {
        'production': {
            'format': '%(asctime)s [%(levelname)s] %(process)d %(thread)d '
                      '%(pathname)s:%(lineno)d %(message)s'
        },
    },
    #Handler settings
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': '/var/log/{}/app.log'.format(PROJECT_NAME),
            'formatter': 'production',
        },
    },
    #Logger settings
    'loggers': {
        #A logger that picks up logs for all applications you add
        '': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': False,
        },
        #A logger that picks up all the logs that Django itself outputs
        'django': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': False,
        },
    },
}

Example of use

views.py


import logging

logger = logging.getLogger(__name__)
logger.info("log info test!")
logger.error("log error test!")

The log has 5 levels according to its importance. You can output the log by letting logger execute the method with the same name as the log level as in the above usage example.

name Use
DEBUG Debug recording
INFO Record of normal operation
WARNING Warning record
ERROR Serious problems such as errors
CRITICAL Fatal problems such as system outages

Let's look at the main setting items

disable_existing_loggers In the case of Ture, all loggers not defined in the configuration file will be disabled. At this stage, you may be wondering "What is a logger that is not defined in the configuration file?", But the meaning is that all loggers with names that are not defined in the ** logger ** item described later are disabled. Will be done. ** Basically False is OK **, but it has been verified in detail in this article, so please check if you are interested.

formatters Formatting of log output. If you set it properly here, the log output format will be aligned and the log will be easier to see, so you can think that ** setting is required **. What do% (asctime) and% (levelname) mean in Official Documents in Japanese It is described in an easy-to-understand manner.

handlers This is the setting for the log output method.

loggers This is the logger setting that is actually used from the app. The logger defined by "''" is a description that follows the output example.

import logging
logger = logging.getLogger(__name__)

You can get it from each application. Basically, it's enough to have this and the logger settings that django itself outputs.

The following is an explanation of propagate. The logger can actually have a ** namespace **. As an example, define'logA'and'logA.logB' as shown below.

    'logger': {
        'logA': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': False,
        },
        'logA.logB': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': False,
        },

Then get the logger from the application as follows.

views.py


import logging

logger = logging.getLogger('logA.logB.logC')
logger.info("log info test!")

At this time, logC is not defined, so ** logB is acquired ** as a result. If the specified logger does not exist, it will go up to the namespace above and get the first one found.

Here, if logB and logC are also defined and the property is True, for all logA, logB, logC

logger.info("log info test!")

Is executed. In other words, if the settings of logA, logB, and logC are the same except for the name, ** logs with exactly the same contents will be output three times **. As the name of propagate, the log output instruction is also propagated to the logger in the upper hierarchy. As a usage, set logA for file output, logB for console output, get logA if you only need the file, get logB if you want to output to the console in the development environment etc. Is it an image like that (I have never used it ...).

that's all. At the end, the content was a little complicated, but unless you do something complicated, I think that the basic settings are OK with just the content described in this article. Thank you for your hard work: cat2:

Recommended Posts

[Django] A brief summary of the log output function so that even beginners can understand it.
A brief summary of qubits (beginners)
Basic summary of scraping with Requests that beginners can absolutely understand [Python]
Explaining the classic machine learning "Support Vector Machine (SVM)" so that even high school students can understand it
Tensorflow, it seems that even the eigenvalues of the matrix can be automatically differentiated
# Function that returns the character code of a string
I made a function to crop the image of python openCV, so please use it.
A brief summary of Linux
・ <Slack> Write a function to notify Slack so that it can be quoted at any time (Python)
Here's a brief summary of how to get started with Django
A function that measures the processing time of a method in python
[python] A note that started to understand the behavior of matplotlib.pyplot
Understand the number of input / output parameters of a convolutional neural network
A brief summary of Python collections
Heroku deployment of the first Django app that beginners are addicted to
[For beginners] Super introduction to neural networks that even cats can understand
I didn't understand the behavior of numpy's argsort, so I will summarize it.
How to create a wrapper that preserves the signature of the function to wrap
[Python] Note: A self-made function that finds the area of the normal distribution
Understand the benefits of the Django Rest Framework
A brief summary of Pinax overview #djangoja
[Python] 3 types of libraries that improve log output a little [logzero, loguru, pyrogrus]
To output a value even in the middle of a cell with Jupyter Notebook
How to count the number of elements in Django and output to a template
I failed to install django with pip, so a reminder of the solution
The story of making a web application that records extensive reading with Django
The story of Django creating a library that might be a little more useful
Read the image posted by flask so that it can be handled by opencv
I didn't understand the Resize of TensorFlow so I tried to summarize it visually.
Hackathon's experience that it is most important to understand the feelings of the organizer
The SHA-512 encryption of the password has been scripted so that it can be automated without worrying about the execution environment.