python logging.getlogger_Python 日志打印之logging.getLogger源码分析

本文详细分析了Python logging模块中的getLogger函数,包括其源码解析,介绍了如何根据指定名称获取或创建日志器,以及日志器的层级结构建立过程。通过对Manager和Logger类的理解,阐述了日志器的父级和子级如何关联,以及占位符PlaceHolder的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

日志打印之logging.getLogger源码分析

By:授客 QQ:1033553122

#实践环境

WIN 10

Python 3.6.5

#函数说明

logging.getLogger(name=None)

getLogger函数位于logging/__init__.py脚本

#源码分析

_loggerClass = Logger

# ...略

root = RootLogger(WARNING)

Logger.root = root

Logger.manager = Manager(Logger.root)

# ...略

def getLogger(name=None):

"""

Return a logger with the specified name, creating it if necessary.

If no name is specified, return the root logger.

"""

if name:

return Logger.manager.getLogger(name)

else:

return root

结论:如函数注释所述,如果调用getLogger时,如果没有指定函数参数(即要获取的日志打印器名称)或者参数值不为真,则默认返回root打印器

##Logger.manager.getLogger(self, name)源码分析

该函数位于logging/__init__.py脚本

class Manager(object):

"""

There is [under normal circumstances] just one Manager instance, which

holds the hierarchy of loggers.

"""

def __init__(self, rootnode):

"""

Initialize the manager with the root node of the logger hierarchy.

"""

self.root = rootnode

self.disable = 0

self.emittedNoHandlerWarning = False

self.loggerDict = {}

self.loggerClass = None

self.logRecordFactory = None

def getLogger(self, name):

"""

Get a logger with the specified name (channel name), creating it

if it doesn't yet exist. This name is a dot-separated hierarchical

name, such as "a", "a.b", "a.b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值