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

  • 相关阅读:
    考研打卡_Day018
    如何使用python中的pymysql操作mysql数据库
    Linux系统目录结构和常用目录主要存放内容的说明
    MySQL基础入门使用和命令的使用
    Python中property属性的概论和使用方法
    如何有效的优化自己的网站访问速度
    机器学习中的特征工程学习
    ffmpeg中c语言sdk多媒体互转主要使用的api
    FFmpeg使用c语言sdk实现打印视频的信息
    ffmpeg使用C语言sdk实现抽取视频中的视频数据
  • 原文地址:https://www.cnblogs.com/hf8051/p/11727520.html
Copyright © 2011-2022 走看看