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

 

posted @ 2019-10-23 17:22  goodup  阅读(1842)  评论(0编辑  收藏  举报

如有不对之处,欢迎指出,一起成长