废话少说,先上代码

    1. Filelogger.conf
    2.  
    3. [formatters]
    4. keys=default
    5.  
    6. [formatter_default]
    7. format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
    8. class=logging.Formatter
    9.  
    10. [handlers]
    11. keys=console, error_file
    12.  
    13. [handler_console]
    14. class=logging.StreamHandler
    15. formatter=default
    16. args=tuple()
    17.  
    18. [handler_error_file]
    19. class=logging.FileHandler
    20. level=INFO
    21. formatter=default
    22. args=("logger.log", "a")
    23.  
    24. [loggers]
    25. keys=root
    26.  
    27. [logger_root]
    28. level=DEBUG
    29. formatter=default
    30. handlers=console,error_file
    1. Filelogger.py
    2.  
    3. #!/bin/env python
    4.  
    5. import logging
    6. from logging.config import logging
    7.  
    8. class Test(object):
    9. """docstring for Test"""
    10. def __init__(self):
    11. logging.config.fileConfig("logger.conf")
    12. self.logger = logging.getLogger(__name__)
    13.  
    14. def test_func(self):
    15. self.logger.error('test_func function')
    16.  
    17. class Worker(object):
    18. """docstring for Worker"""
    19. def __init__(self):
    20. logging.config.fileConfig("logger.conf")
    21. self.logger = logging.getLogger(__name__)
    22.  
    23. data_logger = logging.getLogger('data')
    24. handler = logging.FileHandler('./data.log')
    25. fmt = logging.Formatter('%(asctime)s|%(message)s')
    26. handler.setFormatter(fmt)
    27. data_logger.addHandler(handler)
    28. data_logger.setLevel(logging.DEBUG)
    29. self.data_logger = data_logger
    30.  
    31. def test_logger(self):
    32. self.data_logger.error("test_logger function")
    33. instance = Test()
    34. self.data_logger.error("test_logger output")
    35. instance.test_func()
    36.  
    37. def main():
    38. worker = Worker()
    39. worker.test_logger()
    40.  
    41. if __name__ == '__main__':
    42. 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日志。
 
修改后的如下:

  1. Filelogger.conf
  2.  
  3. [formatters]
  4. keys=default, data
  5.  
  6. [formatter_default]
  7. format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
  8. class=logging.Formatter
  9.  
  10. [formatter_data]
  11. format=%(asctime)s|%(message)s
  12. class=logging.Formatter
  13.  
  14. [handlers]
  15. keys=console, error_file, data_file
  16.  
  17. [handler_console]
  18. class=logging.StreamHandler
  19. formatter=default
  20. args=tuple()
  21.  
  22. [handler_error_file]
  23. class=logging.FileHandler
  24. level=INFO
  25. formatter=default
  26. args=("logger.log", "a")
  27.  
  28. [handler_data_file]
  29. class=logging.FileHandler
  30. level=INFO
  31. formatter=data
  32. args=("data_new.log", "a")
  33.  
  34. [loggers]
  35. keys=root, data
  36.  
  37. [logger_root]
  38. level=DEBUG
  39. handlers=console,error_file
  40.  
  41. [logger_data]
  42. level=DEBUG
  43. handlers=data_file
  44. qualname=data
  45. propagate=0
  1. Filelogger.py
  2.  
  3. #!/bin/env python
  4.  
  5. import logging
  6. from logging.config import logging
  7.  
  8. class Test(object):
  9. """docstring for Test"""
  10. def __init__(self):
  11. self.logger = logging.getLogger(__name__)
  12.  
  13. def test_func(self):
  14. self.logger.error('test_func function')
  15.  
  16. class Worker(object):
  17. """docstring for Worker"""
  18. def __init__(self):
  19. logging.config.fileConfig("logger.conf")
  20. self.logger = logging.getLogger(__name__)
  21. self.data_logger = logging.getLogger('data')
  22.  
  23. def test_logger(self):
  24. self.data_logger.error("test_logger function")
  25. instance = Test()
  26. self.data_logger.error("test_logger output")
  27. instance.test_func()
  28.  
  29. def main():
  30. worker = Worker()
  31. worker.test_logger()
  32.  
  33. if __name__ == '__main__':
  34. main()

Python logging模块无法正常输出日志的更多相关文章

  1. python logging模块详解[转]

    一.简单将日志打印到屏幕: import logging logging.debug('debug message') logging.info('info message') logging.war ...

  2. python logging模块使用

    近来再弄一个小项目,已经到收尾阶段了.希望加入写log机制来增加程序出错后的判断分析.尝试使用了python logging模块. #-*- coding:utf-8 -*- import loggi ...

  3. Python logging模块详解

    简单将日志打印到屏幕: import logging logging.debug('debug message') logging.info('info message') logging.warni ...

  4. 读懂掌握 Python logging 模块源码 (附带一些 example)

    搜了一下自己的 Blog 一直缺乏一篇 Python logging 模块的深度使用的文章.其实这个模块非常常用,也有非常多的滥用.所以看看源码来详细记录一篇属于 logging 模块的文章. 整个 ...

  5. (转)python logging模块

    python logging模块 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python ...

  6. [转载]Python logging模块详解

    原文地址: http://blog.csdn.net/zyz511919766/article/details/25136485 简单将日志打印到屏幕: import logging logging. ...

  7. python logging—模块

    python logging模块 python logging提供了标准的日志接口,python logging日志分为5个等级: debug(), info(), warning(), error( ...

  8. 0x03 Python logging模块之Formatter格式

    目录 logging模块之Formatter格式 Formater对象 日志输出格式化字符串 LogRecoder对象 时间格式化字符串 logging模块之Formatter格式 在记录日志是,日志 ...

  9. 0x01 Python logging模块

    目录 Python logging 模块 前言 logging模块提供的特性 logging模块的设计过程 logger的继承 logger在逻辑上的继承结构 logging.basicConfig( ...

随机推荐

  1. IE block my cookie in iframe

    ---恢复内容开始--- There is a severe bug that a leader figured it out in a published project. In IE11, the ...

  2. Java 接口中定义抽象方法有什么意义

    接口方法声明只能是public abstract的,所以不管你在声明的时候加不加abstract,都是可以的.Java 8开始,接口还引入了默认方法,也就是可以给接口的方法提供默认的实现,默认方法应当 ...

  3. [WASM] Create and Run a Native WebAssembly Function

    In this introduction, we show a simple WebAssembly function that returns the square root of a number ...

  4. u-boot-2011.06在基于s3c2440开发板的移植之引导内核与加载根文件系统

    http://www.linuxidc.com/Linux/2012-09/70510.htm  来源:Linux社区  作者:赵春江 uboot最主要的功能就是能够引导内核启动.本文就介绍如何实现该 ...

  5. width:100%和width:inherit

    前几天遇到过这么一个问题.我想让子盒子的宽度等于父盒子的宽度.父盒子宽度为一个具体值比如说200px.我将子盒子宽度设为了100%.按道理说应该是可以等于父盒子的宽度的,但结果并没有,而是通栏了.然后 ...

  6. ETL概述 分类: H2_ORACLE 2013-08-23 10:36 344人阅读 评论(0) 收藏

    转自:http://blog.csdn.net/leosoft/article/details/4279536 ETL,Extraction-Transformation-Loading的缩写,中文名 ...

  7. 使用Opencv中matchTemplate模板匹配方法跟踪移动目标

    模板匹配是一种在图像中定位目标的方法,通过把输入图像在实际图像上逐像素点滑动,计算特征相似性,以此来判断当前滑块图像所在位置是目标图像的概率. 在Opencv中,模板匹配定义了6种相似性对比方式: C ...

  8. Android自定义组件系列【6】——进阶实践(3)

    上一篇<Android自定义组件系列[5]--进阶实践(2)>继续对任老师的<可下拉的PinnedHeaderExpandableListView的实现>进行了分析,这一篇计划 ...

  9. Java NIO学习笔记之基本概念

    一.缓冲区操作 缓冲区,以及缓冲区如何工作,是所有 I/O 的基础.所谓"输入/输出"讲的无非就是把数据移进或移出缓冲区. 进程使用 read( )系统调用,要求其缓冲区被填满.内 ...

  10. zookeeper无法启动&quot;Unable to load database on disk&quot;

    自己的虚拟机集群.一次强制关机后,发现slave2的zookeeper起不来了 http://blog.csdn.net/ashic/article/details/47088299 下午5点29:5 ...