zoukankan      html  css  js  c++  java
  • 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。

    调整代码顺序,如下:

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

  • 相关阅读:
    (算法)最长重叠线段或区间
    (算法)判断两个区间是否重叠
    (笔试题)洗牌算法
    (笔试题)和一半的组合数
    (笔试题)删除K位数字
    (C语言)memcpy函数原型的实现
    每天坚持10分钟,改变你的人生
    你是哪种层次的程序员?程序员的四种类型
    2012年,软件开发者薪资大调查
    上班族:不要让自己成为老板的“日用品”!
  • 原文地址:https://www.cnblogs.com/hf8051/p/11727520.html
Copyright © 2011-2022 走看看