How does the Django project properly configure the log of logging

  • 2021-11-02 01:48:06
  • OfStack

Directory Logging Basics Django Logging Module settings. py Recommended Logging Configuration Information

When the Django project is officially deployed and launched, we need to set DEBUG = False. At this point, how should the developer check for any exceptions or errors in the Django program when it is running in the production environment? The answer is log (logging). In a production environment, Django does not automatically generate log files on the server by default, and the administrator will not be notified even if the program fails at error level. This article will teach you how to properly configure logs (logging) in the Django project, let Django generate log log files, and notify administrators when error level failures occur when the program runs.

Basic knowledge of logging

Logs are inseparable from our software programs. It records the running status of the program, and can provide very useful information for us to debug the program and troubleshoot. Every log message records the occurrence of one event. Specifically, it includes:

Event occurrence time Event occurrence location Severity of the event-log level Event content

Log levels are divided into:

DEBUG: Low-level system information for debugging purposes INFO: 1 General System Information WARNING: Information describing minor problems that have occurred. ERROR: Information describing the major problems that have occurred. CRITICAL: Information describing a serious problem that has occurred.

In the Django project, we can set different processing methods for different levels of logs. For example, INFO level and above logs are written to log file for saving, and Error level and above logs are sent directly to the system administrator by mail.

Log Module of Django

The log module of Django is actually the logging module of python. It consists of four parts:

Logger Recorder: Generate and record each log information and level Handler Handler: Submit to the appropriate handler according to the log information level (such as generating files or sending mail) Filters Filter: Filter criteria that need to be satisfied before the log can be processed by a handler (e.g. Debug=True or False) Formaters Formatter: Determines the print output format of each log, either full or simple

An example of an logger recorder is shown below. When the program runs in error, it generates a log message at the level of error. After this record is generated, it will be processed by Handler.


# import the logging library
import logging
#  Obtain logger Instances 
logger = logging.getLogger(__name__)
def my_view(request, arg1, arg):
    ...
    if error_happens:
        # Log an error message
        logger.error('Something went wrong!')

When Debug=True, the log information is output at console by default. Now we also need to configure the log (logging) in the django configuration file so that when Debug = False, the log information will be output to the log file or sent to the system administrator.

settings. py Recommended Log Configuration Information

The following basic configuration information is modified from the logging configuration information recommended for django cookiecutter to fit most projects. If you really want to send and receive mail, you also need to correctly configure the email address Email at settings. py.


#  To ADMINS Sending mail requires configuration 
ADMINS = (
 ('admin_name','your@gmail.com'),
)
MANAGERS = ADMINS
#  Create log Folder of files 
LOG_DIR = os.path.join(BASE_DIR, "logs")

#  Basic configuration, reusable 
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
    "formatters": { #  Two log formats are defined 
        "verbose": { #  Standard 
            "format": "%(levelname)s %(asctime)s %(module)s "
            "%(process)d %(thread)d %(message)s"
        },
        'simple': { #  Simple 
            'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
        },
    },
    "handlers": { #  Defines the 3 Different log processing methods 
        "mail_admins": { #  Only debug=False And Error Above the level, send an email to admin
            "level": "ERROR",
            "filters": ["require_debug_false"],
            "class": "django.utils.log.AdminEmailHandler",
        },
        'file': { # Info Save to log file above level 
            'level': 'INFO', 
            'class': 'logging.handlers.RotatingFileHandler',  #  Save to file, automatically cut according to file size 
            'filename': os.path.join(LOG_DIR,"info.log"),  #  Log file 
            'maxBytes': 1024 * 1024 * 10,  #  Log size  10M
            'backupCount': 2,  #  The number of backups is  2
            'formatter': 'simple', #  Simple format 
            'encoding': 'utf-8',
        },
        "console": { #  Print to terminal console
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "verbose",
        },
    },
    "root": {"level": "INFO", "handlers": ["console"]},
    "loggers": {
        "django.request": { # Django Adj. request Occurrence error Will automatically record 
            "handlers": ["mail_admins"],
            "level": "ERROR",
            "propagate": True,  #  To or not to a higher level logger Transfer 
        },
        "django.security.DisallowedHost": { #  For absence  ALLOWED_HOSTS  Do not send error messages for requests in 
            "level": "ERROR",
            "handlers": ["console", "mail_admins"],
            "propagate": True,
        },
    },
}

The above is the Django project how to correctly configure the log (logging) details, more about Django correctly configure the log information please pay attention to other related articles on this site!


Related articles: