有這麼一段python代碼python
import threading import time import requests from decimal import Decimal, ROUND_DOWN import logging import os import sys import randomfrom utils import common, filter, cache from configs import settings logging.basicConfig(level=logging.INFO, format='%(levelname)s %(asctime)s [line:%(lineno)d] %(message)s')
無論怎麼設置basicConfig裏的值,一直都沒法生效,後來看到一個說法:在調用basicConfig函數以前,由於導入了其餘包,而其餘包裏又導入了logging包,就致使設置basicConfig不成功。一排查,確實在common和cache包裏又導入了logging。app
調整代碼順序,以下:dom
import os import sys import random import threading import time import requests from decimal import Decimal, ROUND_DOWN import logging logging.basicConfig(level=logging.INFO, format='%(levelname)s %(asctime)s [line:%(lineno)d] %(message)s') this_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(this_dir, '..')) from utils import common, filter, cache from configs import settings
確實,就生效了。函數
經排查,「在調用basicConfig函數以前,由於導入了其餘包,而其餘包裏又導入了logging包,就致使設置basicConfig不成功」 這個說法還不夠,應該是 「在調用basicConfig函數以前,由於導入了其餘包,而其餘包裏又導入了logging包,且也調用了basicConfig函數,就致使設置basicConfig不成功」。ui
爲何呢?上 basicConfig 源碼:this
def basicConfig(**kwargs): _acquireLock() try: if len(root.handlers) == 0: filename = kwargs.get("filename") if filename: mode = kwargs.get("filemode", 'a') hdlr = FileHandler(filename, mode) else: stream = kwargs.get("stream") hdlr = StreamHandler(stream) fs = kwargs.get("format", BASIC_FORMAT) dfs = kwargs.get("datefmt", None) fmt = Formatter(fs, dfs) hdlr.setFormatter(fmt) root.addHandler(hdlr) level = kwargs.get("level") if level is not None: root.setLevel(level) finally: _releaseLock()
由於,在其餘地方已經調用過了basicConfig函數,在當前文件中再調用basicConfig的時候,會發現 len(root.handlers) 的長度已經再也不爲0了,因此致使不走 if len(root.handlers) == 0,因此設置的日誌格式無效。spa