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

  • 相关阅读:
    Autofac-案例
    Autofac-DynamicProxy(AOP动态代理)
    AutoFac注册2-程序集
    MVC添加跨域支持Cros
    redis笔记3-基础知识与常用命令
    Redis笔记2-Redis安装、配置
    Redis笔记-八种数据类型使用场景
    ActionResult源码分析笔记
    .NET UrlRouting原理
    webapi使用ExceptionFilterAttribute过滤器
  • 原文地址:https://www.cnblogs.com/hf8051/p/11727520.html
Copyright © 2011-2022 走看看