废话少说,先上代码

  • 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 日志模块实例的更多相关文章

  1. python日志模块logging

    python日志模块logging   1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...

  2. python日志模块

    许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系 统的运行状况进行跟踪.在.NET平台中,有非常著名的第三方开源日志组件log4net,c++中,有人们熟悉的log4c ...

  3. Python日志模块logging用法

    1.日志级别 日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICAL. DEBUG:详细的信息,通常只出现在诊断问题上 INFO:确认一切按预期运行 ...

  4. python日志模块的使用

    学习一下python的日志模块logging,可以参考如下博客,写得很详细 https://www.cnblogs.com/yyds/p/6901864.html https://www.cnblog ...

  5. Python日志模块logging&JSON

    日志模块的用法 json部分 先开一段测试代码:注意  str可以直接处理字典   eval可以直接将字符串转成字典的形式 dic={'key1':'value1','key2':'value2'} ...

  6. python日志模块logging学习

    介绍 Python本身带有logging模块,其默认支持直接输出到控制台(屏幕),或者通过配置输出到文件中.同时支持TCP.HTTP.GET/POST.SMTP.Socket等协议,将日志信息发送到网 ...

  7. python日志模块笔记

    前言 在应用中记录日志是程序开发的重要一环,也是调试的重要工具.但却很容易让人忽略.之前用flask写的一个服务就因为没有处理好日志的问题导致线上的错误难以察觉,修复错误的定位也很困难.最近恰好有时间 ...

  8. Python 日志模块详解

    前言 我们知道查看日志是开发人员日常获取信息.排查异常.发现问题的最好途径,日志记录中通常会标记有异常产生的原因.发生时间.具体错误行数等信息,这极大的节省了我们的排查时间,无形中提高了编码效率.所以 ...

  9. Python日志模块的管理(二)

    日志模块可以通过封装一个类,也可以通过配置文件取管理 新建1个log.ini文件 [loggers] keys=root [handlers] keys=fileHandler,streamHandl ...

随机推荐

  1. Hadoop详解一:Hadoop简介

    从数据爆炸开始... 一. 第三次工业革命        第一次:18世纪60年代,手工工厂向机器大生产过渡,以蒸汽机的发明和使用为标志.      第二次:19世纪70年代,各种新技术新发明不断被应 ...

  2. Eclipse JDK的安装

    1.jdk安装无法配置,eclipse绿色版安装无法打开,系统的版本问题(32位和64位): 2.Eclipse下载PDT时,可以如下安装: 三个地方设置好即可,其实第三个选第一个的话会出现无法提供函 ...

  3. 用PS给图标添加外发光效果

    最近在做app的时候用到了图标需要根据点击和非点击显示两种状态(原始状态和外发光状态). 如下图: 没办法,因为这是毕业设计的东西,总不能叫同事帮忙处理下.所以自己充当了回美工. 做法如下: 1.打开 ...

  4. tp框架

    <?php namespace Admin\Controller; use Think\Controller; class DengluController extends Controller ...

  5. 简易的AJAX工具[转]

    关键字: ajax 1.创建XMLHttpRequest对象的js文件 Ajax.js function Ajax(){    var xmlHttp=null;    if(window.XMLHt ...

  6. Selenium2(java)启动常用浏览器 三

    默认启动firefox浏览器 Webdriver driver = new FirefoxDriver(); 启动谷歌浏览器 配置chromedriver WebDriver driver; Syst ...

  7. ubuntu 16.04 php 安装curl方法

    先查看自己的php是否已经安装了curl.方法如下:1.在web服务器目录( Ubuntu下的通常为 /var/www )新建test.php文件2.编辑文件,键入下面一行代码:<?php ph ...

  8. python2与python3编码问题

    python2: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 33: 解决办法: 在报错的页面添加代码:  ...

  9. xlrd(开excel表格)

    打来表格 wb = xlrd.open_workbook('example.xlsx') 选择sheet sh=wb.sheet_by_index(序号) 表格的行数 sh.nrows 选取第m行第n ...

  10. 【Xilinx-VDMA模块学习】-01- VDMA IP的GUI配置介绍

    使用的是Vivado 2015.4,XC7Z020, AXI Video Direct Memory Acess(6.2). 在我的系统中,GUI配置图片如下:(其实和默认配置没有太大区别) 下面介绍 ...