Django配置日志系统
在项目主配置文件中加入本代码段
LOGGING = {
'version': 1,
'disable_existing_loggers': False, # Disable an existing logger
'formatters': { # Log Information Format
'standard': { # Detailed log format
'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
'[%(levelname)s][%(message)s]'
},
'simple': { # Simple log format
'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
},
'collect': { # Define a special log format
'format': '%(message)s'
}
},
'filters': { # Filter the logs
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
# Processor
'handlers': {
# Print at terminal
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'], # The log is printed on the screen only when Django debug is True
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
# Default
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # Save to file
'filename': os.path.join(BASE_DIR, "./project_information/logs/xzy_mall.log"), # log_file Location
'maxBytes': 1024 * 1024 * 30, # log_size 30M
'backupCount': 10, # Maximum number of backups
'formatter': 'standard',
'encoding': 'utf-8',
},
# It is for error logging
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler', # save to log file
'filename': os.path.join(BASE_DIR, "./project_information/logs/xzy_mall.log"), # log file
'maxBytes': 1024 * 1024 * 30, # log_size 30M
'backupCount': 10,
'formatter': 'standard',
'encoding': 'utf-8',
},
# A specific log is defined to collect specific information
'collect': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(BASE_DIR, "./project_information/logs/xzy_mall.log"),
'maxBytes': 1024 * 1024 * 30, # log_size 30M
'backupCount': 10,
'formatter': 'collect',
'encoding': "utf-8"
}
},
'loggers': {
'': { # The default logger application is configured as follows
'handlers': ['default', 'console', 'error'], # You can remove the console when you are online
'level': 'DEBUG',
'propagate': True, # Pass to no higher level logger
},
'collect': { # The 'collect' logger is also handled separately
'handlers': ['console', 'collect'],
'level': 'INFO',
},
},
}
最后在配置目录下创建文件夹logs与自定义日志文件(.log文件)
执行运行Django项目
成功则会显示如上日志信息