- 定义日志记录器
- 可以在setting.py里设置日志记录器
# 自定义日志输出信息 LOGGING = { ‘version‘: 1, ‘disable_existing_loggers‘: True, ‘formatters‘: { ‘standard‘: { ‘format‘: ‘%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s‘} #日志格式 }, ‘filters‘: { }, ‘handlers‘: { ‘mail_admins‘: { ‘level‘: ‘ERROR‘, ‘class‘: ‘django.utils.log.AdminEmailHandler‘, ‘include_html‘: True, }, ‘default‘: { ‘level‘:‘DEBUG‘, ‘class‘:‘logging.handlers.RotatingFileHandler‘, ‘filename‘: ‘log/all.log‘, #日志输出文件 ‘maxBytes‘: 1024*1024*5, #文件大小 ‘backupCount‘: 5, #备份份数 ‘formatter‘:‘standard‘, #使用哪种formatters日志格式 }, ‘error‘: { ‘level‘:‘ERROR‘, ‘class‘:‘logging.handlers.RotatingFileHandler‘, ‘filename‘: ‘log/error.log‘, ‘maxBytes‘:1024*1024*5, ‘backupCount‘: 5, ‘formatter‘:‘standard‘, }, ‘console‘:{ ‘level‘: ‘DEBUG‘, ‘class‘: ‘logging.StreamHandler‘, ‘formatter‘: ‘standard‘ }, ‘request_handler‘: { ‘level‘:‘DEBUG‘, ‘class‘:‘logging.handlers.RotatingFileHandler‘, ‘filename‘: ‘log/script.log‘, ‘maxBytes‘: 1024*1024*5, ‘backupCount‘: 5, ‘formatter‘:‘standard‘, }, ‘scprits_handler‘: { ‘level‘:‘DEBUG‘, ‘class‘:‘logging.handlers.RotatingFileHandler‘, ‘filename‘:‘log/script.log‘, ‘maxBytes‘: 1024*1024*5, ‘backupCount‘: 5, ‘formatter‘:‘standard‘, } }, ‘loggers‘: { ‘django‘: { ‘handlers‘: [‘default‘, ‘console‘], ‘level‘: ‘DEBUG‘, ‘propagate‘: False }, ‘django.request‘: { ‘handlers‘: [‘request_handler‘], ‘level‘: ‘DEBUG‘, ‘propagate‘: False, }, ‘scripts‘: { ‘handlers‘: [‘scprits_handler‘], ‘level‘: ‘INFO‘, ‘propagate‘: False }, ‘blog.views‘: { ‘handlers‘: [‘default‘, ‘error‘], ‘level‘: ‘DEBUG‘, ‘propagate‘: True }, } }
- 在views.py里调用日志记录器
import logging #调用日志记录器 from django.shortcuts import render logging = logging.getLogger(‘blog.views‘) #调用日志器中的 ‘blog.views‘ 函数 # Create your views here. def index(request): try: file = open(‘sss.txt‘,‘r‘) #打开一个不存在的文件 except Exception as e: logging.error(e) #捕获错误,记录入日志中 return render(request, ‘index.html‘, locals())
时间: 2024-10-10 23:23:58