1. 程式人生 > >logging模組日誌重複列印問題

logging模組日誌重複列印問題

小問題解析

  今天練習中介軟體時 出現的小問題,分享一下,程式碼簡陋,湊合看吧

  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)

將 例項化個物件 設定物件等級  寫入那個檔案  寫入檔案時觸發的等級 四句話 挪到類上邊就行。