小问题解析
今天练习中间件时 出现的小问题,分享一下,代码简陋,凑合看吧
longgin 打印时 第一次打印一次日志 第二次打印两次日志,逐次递增
from django.utils.deprecation import MiddlewareMixin import logging lis =[] class Middlel(MiddlewareMixin): def process_request(self,request): lis.append(request.META) for i in lis: log = i['HTTP_USER_AGENT'] logger = logging.getLogger() logger.setLevel(logging.INFO) fh = logging.FileHandler("1.log") fh.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] " "- %(levelname)s: %(message)s") fh.setFormatter(formatter) logger.addHandler(fh) logger.critical(log)
更改后的代码
from django.utils.deprecation import MiddlewareMixin import logging lis =[] logger = logging.getLogger() logger.setLevel(logging.INFO) fh = logging.FileHandler("1.log") fh.setLevel(logging.DEBUG) class Middlel(MiddlewareMixin): def process_request(self,request): lis.append(request.META) for i in lis: log = i['HTTP_USER_AGENT'] formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] " "- %(levelname)s: %(message)s") fh.setFormatter(formatter) logger.addHandler(fh) logger.critical(log)
将 实例化个对象 设定对象等级 写入那个文件 写入文件时触发的等级 四句话 挪到类上边就行。