python日志记录模块实例及改进

yipeiwu_com5年前Python基础

python 打印对象的所有属性值:

def prn_obj(obj):
  print '\n'.join(['%s:%s' % item for item in obj.__dict__.items()])

Python logger对象属性(由上述函数获取的)

name:get_data
parent:<logging.RootLogger instance at 0x1d8bd88>
handlers:[<logging.FileHandler instance at 0x21bcc68>]
level:10
disabled:1   #当前的logger是否有效,默认为0
manager:<logging.Manager instance at 0x1d8bea8>
propagate:0   #是否将本级日志
filters:[]
 

部分日志无法输出

File:logger.conf

 
[formatters]
keys=default
 
[formatter_default]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
class=logging.Formatter
 
[handlers]
keys=console, error_file
 
[handler_console]
class=logging.StreamHandler
formatter=default
args=tuple()
 
[handler_error_file]
class=logging.FileHandler
level=INFO
formatter=default
args=("logger.log", "a")
 
[loggers]
keys=root
 
[logger_root]
level=DEBUG
formatter=default
handlers=console,error_file

File:logger.py

 
#!/bin/env python
 
import logging
from logging.config import logging
 
class Test(object):
  """docstring for Test"""
  def __init__(self):
    logging.config.fileConfig("logger.conf")
    self.logger = logging.getLogger(__name__)
 
  def test_func(self):
    self.logger.error('test_func function')
 
class Worker(object):
  """docstring for Worker"""
  def __init__(self):
    logging.config.fileConfig("logger.conf")
    self.logger = logging.getLogger(__name__)
 
    data_logger = logging.getLogger('data')
    handler = logging.FileHandler('./data.log')
    fmt = logging.Formatter('%(asctime)s|%(message)s')
    handler.setFormatter(fmt)
    data_logger.addHandler(handler)
    data_logger.setLevel(logging.DEBUG)
    self.data_logger = data_logger
 
  def test_logger(self):
    self.data_logger.error("test_logger function")
    instance = Test()
    self.data_logger.error("test_logger output")
    instance.test_func()
 
 
def main():
  worker = Worker()
  worker.test_logger()
 
if __name__ == '__main__':
  main()
 

问题一:测试过程中,只能打印出test_logger function一条语句
问题二:明明只在data_logger中打印出语句,但是logger的日志中也出现了相关的日志。

问题一解决方案:

利用python -m pdb logger.py 语句对脚本进行调试发现,在执行instance = Test()语句后,通过print '\n'.join(['%s:%s' % item for item in self.data_logger.__dict__.items()])调试语句看到data_logger的disable属性值由0变成了True,此时logger的对应属性也发生了相同的变化。这种变化导致了logger对象停止记录日志。参考python  logging模块的相关手册发现“The fileConfig() function takes a default parameter, disable_existing_loggers, which defaults to True for reasons of backward compatibility. This may or may not be what you want, since it will cause any loggers existing before the fileConfig() call to be disabled unless they (or an ancestor) are explicitly named in the configuration.” 的说明,即调用fileconfig()函数会将之前存在的所有logger禁用。在python 2.7版本该fileConfig()函数添加了一个参数,logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True),可以显式的将disable_existing_loggers设置为FALSE来避免将原有的logger禁用。将上述代码中的Test类中的logging.config.fileConfig函数改成logging.config.fileConfig("./logger.conf", disable_existing_loggers=0)就可以解决问题。 不过该代码中由于位于同一程序内,可以直接用logging.getLogger(LOGGOR_NAME)函数引用同一个logger,不用再调用logging.config.fileConfig函数重新加载一遍了。

问题二解决方案:

logger对象有个属性propagate,如果这个属性为True,就会将要输出的信息推送给该logger的所有上级logger,这些上级logger所对应的handlers就会把接收到的信息打印到关联的日志中。logger.conf配置文件中配置了相关的root logger的属性,这个root logger就是默认的logger日志。
 
修改后的如下:

File:logger.conf

 
[formatters]
keys=default, data
 
[formatter_default]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
class=logging.Formatter
 
[formatter_data]
format=%(asctime)s|%(message)s
class=logging.Formatter
 
[handlers]
keys=console, error_file, data_file
 
[handler_console]
class=logging.StreamHandler
formatter=default
args=tuple()
 
[handler_error_file]
class=logging.FileHandler
level=INFO
formatter=default
args=("logger.log", "a")
 
[handler_data_file]
class=logging.FileHandler
level=INFO
formatter=data
args=("data_new.log", "a")
 
[loggers]
keys=root, data
 
[logger_root]
level=DEBUG
handlers=console,error_file
 
[logger_data]
level=DEBUG
handlers=data_file
qualname=data
propagate=0
 

File:logger.py

 
#!/bin/env python
 
import logging
from logging.config import logging
 
class Test(object):
  """docstring for Test"""
  def __init__(self):
    self.logger = logging.getLogger(__name__)
 
  def test_func(self):
    self.logger.error('test_func function')
 
class Worker(object):
  """docstring for Worker"""
  def __init__(self):
    logging.config.fileConfig("logger.conf")
    self.logger = logging.getLogger(__name__)
    self.data_logger = logging.getLogger('data')
 
  def test_logger(self):
    self.data_logger.error("test_logger function")
    instance = Test()
    self.data_logger.error("test_logger output")
    instance.test_func()
 
 
def main():
  worker = Worker()
  worker.test_logger()
 
if __name__ == '__main__':
  main()

相关文章

python寻找list中最大值、最小值并返回其所在位置的方法

实例如下所示: c = [-10,-5,0,5,3,10,15,-20,25] print c.index(min(c)) # 返回最小值 print c.index(max(c)...

Python统计日志中每个IP出现次数的方法

本文实例讲述了Python统计日志中每个IP出现次数的方法。分享给大家供大家参考。具体如下: 这脚本可用于多种日志类型,本人测试MDaemon的all日志文件大小1.23G左右,分析用时...

python 实现兔子生兔子示例

如下所示: # -*- coding: utf-8 -*- # 简述:话说有一对可爱的兔子,出生后的第三个月开始,每一月都会生一对小兔子。 # 当小兔子长到第三个月后,也会每个月再生...

正确理解python中的关键字“with”与上下文管理器

前言 如果你有阅读源码的习惯,可能会看到一些优秀的代码经常出现带有 “with” 关键字的语句,它通常用在什么场景呢?今天就来说说 with 和 上下文管理器。 对于系统资源如文件、数据...

浅谈python中的__init__、__new__和__call__方法

前言 本文主要给大家介绍关于python中__init__、__new__和__call__方法的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍: 任何事物都有一个...