Python日志打印里logging.getLogger源码分析详解


Posted in Python onJanuary 17, 2021

实践环境

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.c" or similar.
 
    If a PlaceHolder existed for the specified name [i.e. the logger
    didn't exist but a child of it did], replace it with the created
    logger and fix up the parent/child references which pointed to the
    placeholder to now point to the logger.
    """
    rv = None
    if not isinstance(name, str):
      raise TypeError('A logger name must be a string')
    _acquireLock()
    try:
      if name in self.loggerDict:
        rv = self.loggerDict[name]
        if isinstance(rv, PlaceHolder):
          ph = rv
          rv = (self.loggerClass or _loggerClass)(name)
          rv.manager = self
          self.loggerDict[name] = rv
          self._fixupChildren(ph, rv)
          self._fixupParents(rv)
      else:
        rv = (self.loggerClass or _loggerClass)(name) # _loggerClass = Logger
        rv.manager = self
        self.loggerDict[name] = rv
        self._fixupParents(rv)
    finally:
      _releaseLock()
    return rv

Logger源码分析

_nameToLevel = {
  'CRITICAL': CRITICAL,
  'FATAL': FATAL,
  'ERROR': ERROR,
  'WARN': WARNING,
  'WARNING': WARNING,
  'INFO': INFO,
  'DEBUG': DEBUG,
  'NOTSET': NOTSET,
}
 
# ...略
 
def _checkLevel(level):
  if isinstance(level, int):
    rv = level
  elif str(level) == level:
    if level not in _nameToLevel:
      raise ValueError("Unknown level: %r" % level)
    rv = _nameToLevel[level]
  else:
    raise TypeError("Level not an integer or a valid string: %r" % level)
  return rv
 
# ...略
class PlaceHolder(object):
  """
  PlaceHolder instances are used in the Manager logger hierarchy to take
  the place of nodes for which no loggers have been defined. This class is
  intended for internal use only and not as part of the public API.
  """
  def __init__(self, alogger):
    """
    Initialize with the specified logger being a child of this placeholder.
    """
    self.loggerMap = { alogger : None }
 
  def append(self, alogger):
    """
    Add the specified logger as a child of this placeholder.
    """
    if alogger not in self.loggerMap:
      self.loggerMap[alogger] = None
 
 
 
class Logger(Filterer):
  """
  Instances of the Logger class represent a single logging channel. A
  "logging channel" indicates an area of an application. Exactly how an
  "area" is defined is up to the application developer. Since an
  application can have any number of areas, logging channels are identified
  by a unique string. Application areas can be nested (e.g. an area
  of "input processing" might include sub-areas "read CSV files", "read
  XLS files" and "read Gnumeric files"). To cater for this natural nesting,
  channel names are organized into a namespace hierarchy where levels are
  separated by periods, much like the Java or Python package namespace. So
  in the instance given above, channel names might be "input" for the upper
  level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
  There is no arbitrary limit to the depth of nesting.
  """
  def __init__(self, name, level=NOTSET):
    """
    Initialize the logger with a name and an optional level.
    """
    Filterer.__init__(self)
    self.name = name
    self.level = _checkLevel(level)
    self.parent = None
    self.propagate = True
    self.handlers = []
    self.disabled = False
 
  # ... 略

结论:如果调用logging.getLogger()时,有指定日志打印器名称,且名称为真(不为空字符串,0,False等False值),

1)如果名称为不存在的日志打印器名称,则,且参数值为真,但是即要获取的日志打印器名称)或者参数值不为真,则创建一个名为给定参数值的日志打印器,该日志打印器,默认级别默认为NOTSET,disable_existing_loggers配置为False,propagate配置为True。然后在日志打印器字典中记录该名称和日志打印器的映射关系,接着调用 _fixupParents(创建的日志打印器实例)类实例方法--为日志打印器设置上级日志打印器,最后返回该日志打印器。

2)如果名称已存在日志打印器名称,则获取该日志打印器,然后判断日志打印器是否为PlaceHolder类实例,如果是,则创建一个名为所给参数值的日志打印器,同第1)点,该日志打印器,默认级别默认为NOTSET,disable_existing_loggers配置为False,propagate配置为True。然后在日志打印器字典中记录该名称和日志打印器的映射关系,接着调用 _fixupParents(创建的打印器实例)类实例方法,_fixupChildren(PlaceHolder类实例--根据名称获取的日志打印器,新建的日志打印器实例)--为新建日志打印器设置上级日志打印器,为PlaceHolder类实例现有下级PlaceHolder日志打印器实例重新设置上级日志打印器,最后返回该日志打印器。

_fixupParents及_fixupChildren函数源码分析

# _fixupParents
 
# ...略
class Manager(object):
  # ...略
  def _fixupParents(self, alogger):
    """
    Ensure that there are either loggers or placeholders all the way
    from the specified logger to the root of the logger hierarchy.
    """
    name = alogger.name # 获取日志打印器名称
    i = name.rfind(".")
    rv = None # 存放alogger日志打印器的上级日志打印器
    while (i > 0) and not rv: # 如果名称中存在英文的点,并且找到上级日志打印器
      substr = name[:i] # 获取名称中位于最后一个英文的点的左侧字符串(暂且称至为 点分上级)
      if substr not in self.loggerDict: # 如果 点分上级 不存在日志打印器字典中
        self.loggerDict[substr] = PlaceHolder(alogger) # 创建PlaceHolder实例作为 点分上级 对应的日志打印器 # 继续查找点分上级日志打印器 # 注意,这里的PlaceHolder仅是占位用,不是真的打印器,这里为了方便描述,暂且称之为PlaceHolder日志打印器
      else: # 否则
        obj = self.loggerDict[substr] # 获取 点分上级 对应的日志打印器
        if isinstance(obj, Logger): # 如果为Logger实例,如果是,则跳出循环,执行 # 为日志打印器设置上级
          rv = obj
        else: # 否则
          assert isinstance(obj, PlaceHolder) # 断言它为PlaceHolder的实例
          obj.append(alogger) # 把日志打印器添加为点分上级对应的PlaceHolder日志打印器实例的下级日志打印器 执行 # 继续查找点分上级日志打印器
      i = name.rfind(".", 0, i - 1) # 继续查找点分上级日志打印器
    if not rv: # 找不到点分上级、或者遍历完所有点分上级,都没找到上级日志打印器
      rv = self.root # 则 把root日志打印器设置为alogger日志打印器的上级日志打印器
    alogger.parent = rv # 为日志打印器设置上级
 
 
 
  def _fixupChildren(self, ph, alogger):
    """
    Ensure that children of the placeholder ph are connected to the
    specified logger.
    """
    name = alogger.name # 获取日志打印器名称
    namelen = len(name) # 获取日志打印器名称长度
    for c in ph.loggerMap.keys(): # 遍历获取的PlaceHolder日志打印器实例的子级日志打印器
      #The if means ... if not c.parent.name.startswith(nm)
      if c.parent.name[:namelen] != name: # 如果PlaceHolder日志打印器实例名称不以alogger日志打印器名称为前缀,
        alogger.parent = c.parent # 那么,设置alogger日志打印器的上级日志打印器为PlaceHolder日志打印器
        c.parent = alogger # 设置alogger日志打印器为PlaceHolder日志打印器原有下级PlaceHolder日志打印器的上级

结论:日志打印器都是分父子级的,这个父子层级是怎么形成的,参见上述函数代码注解

到此这篇关于Python日志打印里logging.getLogger源码分析详解的文章就介绍到这了,更多相关Python logging.getLogger源码分析内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python快速排序代码实例
Nov 21 Python
python海龟绘图实例教程
Jul 24 Python
Python数据结构之翻转链表
Feb 25 Python
Python设计模式之观察者模式简单示例
Jan 10 Python
Python面向对象之类和对象实例详解
Dec 10 Python
用Q-learning算法实现自动走迷宫机器人的方法示例
Jun 03 Python
python傅里叶变换FFT绘制频谱图
Jul 19 Python
python获取网络图片方法及整理过程详解
Dec 20 Python
使用Python+selenium实现第一个自动化测试脚本
Mar 17 Python
vscode+PyQt5安装详解步骤
Aug 12 Python
python 中的命名空间,你真的了解吗?
Aug 19 Python
Python数据可视化之Seaborn的安装及使用
Apr 19 Python
Python中的面向接口编程示例详解
Jan 17 #Python
Python学习之time模块的基本使用
Jan 17 #Python
python中re模块知识点总结
Jan 17 #Python
史上最详细的Python打包成exe文件教程
Jan 17 #Python
python制作微博图片爬取工具
Jan 16 #Python
python工具——Mimesis的简单使用教程
Jan 16 #Python
Python 内存管理机制全面分析
Jan 16 #Python
You might like
php中session_unset与session_destroy的区别分析
2011/06/16 PHP
getimagesize获取图片尺寸实例
2014/11/15 PHP
ext form 表单提交数据的方法小结
2008/08/08 Javascript
JavaScript获取GridView选择的行内容
2009/04/14 Javascript
基于Jquery的标签智能验证实现代码
2010/12/27 Javascript
从零开始学习jQuery (八) 插播:jQuery实施方案
2011/02/23 Javascript
js 实现日期灵活格式化的小例子
2013/07/14 Javascript
推荐 21 款优秀的高性能 Node.js 开发框架
2014/08/18 Javascript
JavaScript判断按钮被点击的方法
2015/12/13 Javascript
js简单实现调整网页字体大小的方法
2016/07/23 Javascript
最棒的Angular2表格控件
2016/08/10 Javascript
Angularjs中使用layDate日期控件示例
2017/01/11 Javascript
浅谈js中用$(#ID)来作为选择器的问题(id重复的时候)
2017/02/14 Javascript
基于jQuery实现一个marquee无缝滚动的插件
2017/03/09 Javascript
zTree jQuery 树插件的使用(实例讲解)
2017/09/25 jQuery
seaJs使用心得之exports与module.exports的区别实例分析
2017/10/13 Javascript
express默认日志组件morgan的方法
2018/04/05 Javascript
Node.js进阶之核心模块https入门
2018/05/23 Javascript
使用vue.js在页面内组件监听scroll事件的方法
2018/09/11 Javascript
JavaScript动态检测密码强度原理及实现方法详解
2019/06/11 Javascript
Vue.js自定义指令学习使用详解
2019/10/19 Javascript
Vue组件通信中非父子组件传值知识点总结
2019/12/05 Javascript
微信小程序 scroll-view的使用案例代码详解
2020/06/11 Javascript
JavaScript 判断数据类型的4种方法
2020/09/11 Javascript
pymongo为mongodb数据库添加索引的方法
2015/05/11 Python
Python中操作mysql的pymysql模块详解
2016/09/13 Python
pycharm中连接mysql数据库的步骤详解
2017/05/02 Python
django将数组传递给前台模板的方法
2019/08/06 Python
python自动保存百度盘资源到百度盘中的实例代码
2019/08/26 Python
Django中提示消息messages的设置方式
2019/11/15 Python
Python函数默认参数常见问题及解决方案
2020/03/26 Python
DataFrame 数据合并实现(merge,join,concat)
2020/06/14 Python
英国领先的鞋类零售商和顶级品牌的官方零售商:Wynsors
2020/02/17 全球购物
农药学硕士毕业生自荐信
2013/09/25 职场文书
大学生护理专业自荐信
2013/10/03 职场文书
学校党员个人问题整改措施思想汇报
2014/10/08 职场文书