侧边栏壁纸
  • 累计撰写 1,975 篇文章
  • 累计创建 73 个标签
  • 累计收到 20 条评论

目 录CONTENT

文章目录

Python logging debug级别没有输出显示

猿哥
2021-05-28 / 0 评论 / 0 点赞 / 2,787 阅读 / 0 字

问题描述

用python自带的logging包进行日志输出的时候发现有些logging语句没有输出,感到比较奇怪就去查了一下logging文档。然后发现其在设置和引用时的logging level会影响最后的输出。logging包默认对输出分成了6个等级:
这里的分值就代表了相应关键字出现的等级高低,NOTSET最低,CRITICAL最高。高等级的语句会覆盖低等级的语句。 一般我们用logging的时候会先在主程序配置一个logging类的格式,然后在子程序中直接引用即可。如果我们在设置默认格式的时候设置的等级比之后调用是的要高,那么调用的logging语句将不会输出;反之,输出时默认等级也会被调用语句的等级覆盖。
import logging
import sys

def test_log_level():
    # set default logging configuration
    logger = logging.getLogger()    # initialize logging class
    logger.setLevel(logging.DEBUG)  # default log level
    format = logging.Formatter("%(asctime)s - %(message)s")    # output format 
    sh = logging.StreamHandler(stream=sys.stdout)    # output to standard output
    sh.setFormatter(format)
    logger.addHandler(sh)
    
    # use logging to generate log ouput 
    logger.info("this is info")
    logger.debug("this is debug")
    logger.warning("this is warning")
    logging.error("this is error")
    logger.critical("this is critical")

test_log_level()
输出
2016-09-13 18:53:05,966 INFO - this is info
2016-09-13 18:53:05,966 DEBUG - this is debug
2016-09-13 18:53:05,966 WARNING - this is warning
2016-09-13 18:53:05,967 ERROR - this is error
2016-09-13 18:53:05,967 CRITICAL - this is critical
如果我们把logger的等级调高,比如到INFO
logger.setLevel(logging.INFO)
输出结果:
2016-09-13 18:52:37,492 INFO - this is info
2016-09-13 18:52:37,492 WARNING - this is warning
2016-09-13 18:52:37,492 ERROR - this is error
2016-09-13 18:52:37,492 CRITICAL - this is critical

logging.debug的调用没有产生日志,也就是上面说的调用等级没有超过默认等级将不会有输出;而其他的调用等级超过默认等级的时候,日志记录的就是调用等级。

总结:因为一般日志系统中调用最多的就是logging.INFO,所以一般默认的等级设置不会太高选择DEBUG或INFO即可。通过调用logging的不同等级可以方便我们快速查阅标签从而找出bug。所以个人觉得这个logging模块还是需要好好看下文档理解掌握下的。

自用推荐写法:

import logging  # 引入logging模块
logging.basicConfig(format='%(levelname)s:%(funcName)s:%(message)s', level = logging.DEBUG)
logging.getLogger().setLevel(logging.DEBUG)

 

0
博主关闭了所有页面的评论