编程语言
首页 > 编程语言> > python的logging 模块的propagate设置

python的logging 模块的propagate设置

作者:互联网

代码:

import logging
import sys


LOG_FORMAT = '[%(asctime)s PID:%(process)d %(levelname)s %(filename)s %(funcName)s] %(message)s'

sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(LOG_FORMAT)
sh.setFormatter(formatter)

sh2 = logging.StreamHandler(sys.stdout)
formatter2 = logging.Formatter(LOG_FORMAT)
sh2.setFormatter(formatter2)

sh3 = logging.StreamHandler(sys.stdout)
formatter3 = logging.Formatter(LOG_FORMAT)
sh3.setFormatter(formatter3)




lab_logger = logging.getLogger()
lab_logger.handlers = [sh]

lab_logger_2 = logging.getLogger('a')
lab_logger_2.handlers = [sh2]
# lab_logger_2.propagate=False

lab_logger_3 = logging.getLogger('a.b')
lab_logger_3.handlers = [sh3]
# lab_logger_3.propagate=False


lab_logger_3.warning('xxxxxxxxxxxxxxxxxxxxx')

运行结果:

 

 

 

 

修改:

import logging
import sys


LOG_FORMAT = '[%(asctime)s PID:%(process)d %(levelname)s %(filename)s %(funcName)s] %(message)s'

sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(LOG_FORMAT)
sh.setFormatter(formatter)

sh2 = logging.StreamHandler(sys.stdout)
formatter2 = logging.Formatter(LOG_FORMAT)
sh2.setFormatter(formatter2)

sh3 = logging.StreamHandler(sys.stdout)
formatter3 = logging.Formatter(LOG_FORMAT)
sh3.setFormatter(formatter3)




lab_logger = logging.getLogger()
lab_logger.handlers = [sh]

lab_logger_2 = logging.getLogger('a')
lab_logger_2.handlers = [sh2]
# lab_logger_2.propagate=False

lab_logger_3 = logging.getLogger('a.b')
lab_logger_3.handlers = [sh3]
lab_logger_3.propagate=False


lab_logger_3.warning('xxxxxxxxxxxxxxxxxxxxx')

运行结果:

 

 

 

 

 

 

 

参考官方文档:

https://docs.python.org/zh-cn/3/library/logging.html

 

 

可以知道,logging.getLogger()获得的是ROOT记录器,logging.getLogger('a')获得的是名为'a'的记录器,logging.getLogger('a.b')获得的是名为'a.b'的记录器。

从logging的记录器名称来看,从父亲到子代可以理解为:

ROOT>'a'>'a.b'

 

也就是说'a.b','a'记录器的propagate设置为False,'a.b'的记录器进行记录时同时会调用'a'记录器和ROOT记录器进行记录,于是就进行了三次记录,同理,

如果'a'记录器的propagate设置为False,'a.b'的记录器进行记录时则不会调用上层记录器,于是只记录一次。

 

 

propagate设置可以绝对下层记录器记录时是否调用上层记录器,'a.b'记录器为'a'记录器的下层且所有记录器均为ROOT记录器的下层。

 

 

 

====================================================

 

 

参考:

https://www.cnblogs.com/yangxiaolan/p/5965185.html

 

 

====================================================

 

标签:logging,LOG,python,lab,getLogger,propagate,记录器,logger
来源: https://www.cnblogs.com/devilmaycry812839668/p/16201014.html