Use logging to record logs in django projects

premise

Based on existing projects https://blog.csdn.net/qq_38122800/article/details/128583379?spm=1001.2014.3001.5502

1. Modify settings.py

insert image description here
Add the following code to the settings.py file:

First import the module:

import os,time
#配置日志

cur_path = os.path.dirname(os.path.realpath(__file__))  # log_path是存放日志的路径
log_path = os.path.join(os.path.dirname(cur_path), 'logs')
if not os.path.exists(log_path): os.mkdir(log_path)  # 如果不存在这个logs文件夹,就在启动服务时自动创建一个

LOGGING = {
    
    
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
    
    
        # 日志格式
        'standard': {
    
    
            'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] '
                      '[%(levelname)s]- %(message)s'},
        'simple': {
    
      # 简单格式
            'format': '%(levelname)s %(message)s'
        },
    },
    # 过滤
    'filters': {
    
    
    },
    # 定义具体处理日志的方式
    'handlers': {
    
    
        # 默认记录所有日志
        'default': {
    
    
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(log_path, 'all-{}.log'.format(time.strftime('%Y-%m-%d'))),
            'maxBytes': 1024 * 1024 * 5,  # 文件大小
            'backupCount': 5,  # 备份数
            'formatter': 'standard',  # 输出格式
            'encoding': 'utf-8',  # 设置默认编码,否则打印出来汉字乱码
        },
        # 输出错误日志
        'error': {
    
    
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(log_path, 'error-{}.log'.format(time.strftime('%Y-%m-%d'))),
            'maxBytes': 1024 * 1024 * 5,  # 文件大小
            'backupCount': 5,  # 备份数
            'formatter': 'standard',  # 输出格式
            'encoding': 'utf-8',  # 设置默认编码
        },
        # 控制台输出
        'console': {
    
    
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'standard'
        },
        # 输出info日志
        'info': {
    
    
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(log_path, 'info-{}.log'.format(time.strftime('%Y-%m-%d'))),
            'maxBytes': 1024 * 1024 * 5,
            'backupCount': 5,
            'formatter': 'standard',
            'encoding': 'utf-8',  # 设置默认编码
        },
    },
    # 配置用哪几种 handlers 来处理日志
    'loggers': {
    
    
        # 类型 为 django 处理所有类型的日志, 默认调用
        'django': {
    
    
            'handlers': ['default', 'console'],  #处理django自己的日志
            'level': 'INFO',
            'propagate': False
        },
        # log 调用时需要当作参数传入
        'log': {
    
    
            #哪里调用,就处理哪里的日志.这里其实是把info、error的日志分别写在了3个文件里,
            # info对应info,error对应error,并且all中也包含了info和error
            'handlers': ['info','error','default','console'],
            'level': 'INFO',
            'propagate': True
        },
    }
}

2. Call the logging module

Import the logging module in the demo/views.py file and set the logger object

import logging

#设置logger对象
log = logging.getLogger('log')

Then add the code where you need to print the log

log.info(f'查询结果是: {
      
      self.res}')

3. Start the service

When starting the service, you can see that there are more logs folders in the project directory
insert image description here

4. Trigger the behavior of printing logs

Through the interface request and query data, you can see that the terminal has log output, and there are logs written in the files in the logs folder
insert image description here

insert image description here
insert image description here

5. Modify the log processing method

insert image description here
If only the console is left in the settings.py file, the realized function: only print the log on the console, and will not write to the log file. If left: info, the realized function: only write the info and above level log to the info.log file, and will not print on the console
again

6. Appendix

log level

The log is divided into 5 levels, from low to high are:

1.DEBUG
2. INFO
3. WARNING
4. ERROR
5. CRITICAL

illustrate:

DEBUG: Detailed information, usually only found on diagnostic issues
INFO: Confirms that everything is running as expected
WARNING: A sign that something unexpected has happened, or that some problem is in the near future (such as "low disk space"). The software still works as expected.
ERROR: A more serious problem, the software failed to perform some function
CRITICAL: A serious error, which indicates that the program itself may not continue to run

These 5 levels also correspond to 5 logging methods: debug, info, warning, error, and critical. The default is WARNING, which is only tracked when it is at or above WARNING.

Guess you like

Origin blog.csdn.net/qq_38122800/article/details/128634140