python - logging.basicConfig format參數無效


有這么一段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。

調整代碼順序,如下:

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不成功”。

為什么呢?上 basicConfig 源碼:

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,所以設置的日志格式無效。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM