`

[转】Python日志输出——logging模块

 
阅读更多

http://blog.csdn.net/chosen0ne/article/details/7319306

1. logging介绍

        Python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志记录方式。

        logging模块与log4j的机制是一样的,只是具体的实现细节不同。模块提供logger,handler,filter,formatter。

        logger:提供日志接口,供应用代码使用。logger最长用的操作有两类:配置和发送日志消息。可以通过logging.getLogger(name)获取logger对象,如果不指定name则返回root对象,多次使用相同的name调用getLogger方法返回同一个logger对象。

        handler:将日志记录(log record)发送到合适的目的地(destination),比如文件,socket等。一个logger对象可以通过addHandler方法添加0到多个handler,每个handler又可以定义不同日志级别,以实现日志分级过滤显示。

        filter:提供一种优雅的方式决定一个日志记录是否发送到handler。

        formatter:指定日志记录输出的具体格式。formatter的构造方法需要两个参数:消息的格式字符串和日期字符串,这两个参数都是可选的。

        与log4j类似,logger,handler和日志消息的调用可以有具体的日志级别(Level),只有在日志消息的级别大于logger和handler的级别。

 

[python] view plaincopyprint?
 
  1. import logging  
  2. import logging.handlers  
  3.   
  4. LOG_FILE = 'tst.log'  
  5.   
  6. handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes = 1024*1024, backupCounts = 5# 实例化handler   
  7. fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'  
  8.   
  9. formatter = logging.Formatter(fmt)   # 实例化formatter  
  10. handler.setFormatter(formatter)      # 为handler添加formatter  
  11.   
  12. logger = logging.getLogger('tst')    # 获取名为tst的logger  
  13. logger.addHandler(handler)           # 为logger添加handler  
  14. logger.setLevel(logging.DEBUG)  
  15.   
  16. logger.info('first info message')  
  17. logger.debug('first debug message')  

        输出:

 

[plain] view plaincopyprint?
 
  1. 2012-03-04 23:21:59,682 - log_test.py:16 - tst - first info message   
  2. 2012-03-04 23:21:59,682 - log_test.py:17 - tst - first debug message  

        关于formatter的配置,采用的是%(<dict key>)s的形式,就是字典的关键字替换。提供的关键字包括:

 

 

Format Description
%(name)s Name of the logger (logging channel).
%(levelno)s Numeric logging level for the message (DEBUGINFOWARNINGERRORCRITICAL).
%(levelname)s Text logging level for the message ('DEBUG''INFO''WARNING''ERROR''CRITICAL').
%(pathname)s Full pathname of the source file where the logging call was issued (if available).
%(filename)s Filename portion of pathname.
%(module)s Module (name portion of filename).
%(funcName)s Name of function containing the logging call.
%(lineno)d Source line number where the logging call was issued (if available).
%(created)f Time when the LogRecord was created (as returned by time.time()).
%(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
%(asctime)s Human-readable time when the LogRecord was created. By default this is of the form “2003-07-08 16:49:45,896” (the numbers after the comma are millisecond portion of the time).
%(msecs)d Millisecond portion of the time when the LogRecord was created.
%(thread)d Thread ID (if available).
%(threadName)s Thread name (if available).
%(process)d Process ID (if available).
%(message)s The logged message, computed as msg % args.

 

        这个是摘自官网,提供了很多信息。

2. logging的配置

        logging的配置可以采用python代码或是配置文件。python代码的方式就是在应用的主模块中,构建handler,handler,formatter等对象。而配置文件的方式是将这些对象的依赖关系分离出来放在文件中。比如前面的例子就类似于python代码的配置方式。这里看一下采用配置文件的方式。

 

[python] view plaincopyprint?
 
  1. import logging  
  2. import logging.config  
  3.   
  4. logging.config.fileConfig("logging.conf")    # 采用配置文件  
  5.   
  6. # create logger  
  7. logger = logging.getLogger("simpleExample")  
  8.   
  9. # "application" code  
  10. logger.debug("debug message")  
  11. logger.info("info message")  
  12. logger.warn("warn message")  
  13. logger.error("error message")  
  14. logger.critical("critical message")  

        loggin.conf采用了模式匹配的方式进行配置,正则表达式是r'^[(.*)]$',从而匹配出所有的组件。对于同一个组件具有多个实例的情况使用逗号‘,’进行分隔。对于一个实例的配置采用componentName_instanceName配置块。使用这种方式还是蛮简单的。

 

 

[plain] view plaincopyprint?
 
  1. [loggers]  
  2. keys=root,simpleExample  
  3.   
  4. [handlers]  
  5. keys=consoleHandler  
  6.   
  7. [formatters]  
  8. keys=simpleFormatter  
  9.   
  10. [logger_root]  
  11. level=DEBUG  
  12. handlers=consoleHandler  
  13.   
  14. [logger_simpleExample]  
  15. level=DEBUG  
  16. handlers=consoleHandler  
  17. qualname=simpleExample  
  18. propagate=0  
  19.   
  20. [handler_consoleHandler]  
  21. class=StreamHandler  
  22. level=DEBUG  
  23. formatter=simpleFormatter  
  24. args=(sys.stdout,)  
  25.   
  26. [formatter_simpleFormatter]  
  27. format=%(asctime)s - %(name)s - %(levelname)s - %(message)s  
  28. datefmt=  

        在指定handler的配置时,class是具体的handler类的类名,可以是相对logging模块或是全路径类名,比如需要RotatingFileHandler,则class的值可以为:RotatingFileHandler或者logging.handlers.RotatingFileHandler。args就是要传给这个类的构造方法的参数,就是一个元组,按照构造方法声明的参数的顺序。

        输出:

 

 

[plain] view plaincopyprint?
 
  1. 2012-03-06 00:09:35,713 - simpleExample - DEBUG - debug message  
  2. 2012-03-06 00:09:35,713 - simpleExample - INFO - info message  
  3. 2012-03-06 00:09:35,714 - simpleExample - WARNING - warn message  
  4. 2012-03-06 00:09:35,714 - simpleExample - ERROR - error message  
  5. 2012-03-06 00:09:35,714 - simpleExample - CRITICAL - critical message  

        这里还要明确一点,logger对象是有继承关系的,比如名为a.b和a.c的logger都是名为a的子logger,并且所有的logger对象都继承于root。如果子对象没有添加handler等一些配置,会从父对象那继承。这样就可以通过这种继承关系来复用配置。

3. 多模块使用logging

        logging模块保证在同一个python解释器内,多次调用logging.getLogger('log_name')都会返回同一个logger实例,即使是在多个模块的情况下。所以典型的多模块场景下使用logging的方式是在main模块中配置logging,这个配置会作用于多个的子模块,然后在其他模块中直接通过getLogger获取Logger对象即可。

        这里使用上面配置文件:

 

[plain] view plaincopyprint?
 
  1. [loggers]  
  2. keys=root,main  
  3.   
  4. [handlers]  
  5. keys=consoleHandler,fileHandler  
  6.   
  7. [formatters]  
  8. keys=fmt  
  9.   
  10. [logger_root]  
  11. level=DEBUG  
  12. handlers=consoleHandler  
  13.   
  14. [logger_main]  
  15. level=DEBUG  
  16. qualname=main  
  17. handlers=fileHandler  
  18.   
  19. [handler_consoleHandler]  
  20. class=StreamHandler  
  21. level=DEBUG  
  22. formatter=fmt  
  23. args=(sys.stdout,)  
  24.   
  25. [handler_fileHandler]  
  26. class=logging.handlers.RotatingFileHandler  
  27. level=DEBUG  
  28. formatter=fmt  
  29. args=('tst.log','a',20000,5,)  
  30.   
  31. [formatter_fmt]  
  32. format=%(asctime)s - %(name)s - %(levelname)s - %(message)s  
  33. datefmt=  

 

        主模块main.py:

 

[python] view plaincopyprint?
 
  1. import logging  
  2. import logging.config  
  3.   
  4. logging.config.fileConfig('logging.conf')  
  5. root_logger = logging.getLogger('root')  
  6. root_logger.debug('test root logger...')  
  7.   
  8. logger = logging.getLogger('main')  
  9. logger.info('test main logger')  
  10. logger.info('start import module \'mod\'...')  
  11. import mod  
  12.   
  13. logger.debug('let\'s test mod.testLogger()')  
  14. mod.testLogger()  
  15.   
  16. root_logger.info('finish test...')  

        子模块mod.py:

 

 

[python] view plaincopyprint?
 
  1. import logging  
  2. import submod  
  3.   
  4. logger = logging.getLogger('main.mod')  
  5. logger.info('logger of mod say something...')  
  6.   
  7. def testLogger():  
  8.     logger.debug('this is mod.testLogger...')  
  9.     submod.tst()  

        子子模块submod.py:

 

 

[python] view plaincopyprint?
 
  1. import logging  
  2.   
  3. logger = logging.getLogger('main.mod.submod')  
  4. logger.info('logger of submod say something...')  
  5.   
  6. def tst():  
  7.     logger.info('this is submod.tst()...')  

        然后运行python main.py,控制台输出:

 

 

[plain] view plaincopyprint?
 
  1. 2012-03-09 18:22:22,793 - root - DEBUG - test root logger...  
  2. 2012-03-09 18:22:22,793 - main - INFO - test main logger  
  3. 2012-03-09 18:22:22,809 - main - INFO - start import module 'mod'...  
  4. 2012-03-09 18:22:22,809 - main.mod.submod - INFO - logger of submod say something...  
  5. 2012-03-09 18:22:22,809 - main.mod - INFO - logger say something...  
  6. 2012-03-09 18:22:22,809 - main - DEBUG - let's test mod.testLogger()  
  7. 2012-03-09 18:22:22,825 - main.mod - DEBUG - this is mod.testLogger...  
  8. 2012-03-09 18:22:22,825 - main.mod.submod - INFO - this is submod.tst()...  
  9. 2012-03-09 18:22:22,841 - root - INFO - finish test...  

        可以看出,和预想的一样,然后在看一下tst.log,logger配置中的输出的目的地:

 

 

[plain] view plaincopyprint?
 
  1. 2012-03-09 18:22:22,793 - main - INFO - test main logger  
  2. 2012-03-09 18:22:22,809 - main - INFO - start import module 'mod'...  
  3. 2012-03-09 18:22:22,809 - main.mod.submod - INFO - logger of submod say something...  
  4. 2012-03-09 18:22:22,809 - main.mod - INFO - logger say something...  
  5. 2012-03-09 18:22:22,809 - main - DEBUG - let's test mod.testLogger()  
  6. 2012-03-09 18:22:22,825 - main.mod - DEBUG - this is mod.testLogger...  
  7. 2012-03-09 18:22:22,825 - main.mod.submod - INFO - this is submod.tst()...  

        tst.log中没有root logger输出的信息,因为logging.conf中配置了只有main logger及其子logger使用RotatingFileHandler,而root logger是输出到标准输出。

分享到:
评论

相关推荐

    python的logging模块

    用python写程序的,作为一个完整的项目而言,必须要有日志模块,而python的logging模块为我们提供了这么一种很好的机制,很方便的解决了这个问题。

    tyjwan#SE-Notes#日志使用1

    python 日志使用记录参考链接Python日志输出——logging模块Python之日志处理(logging模块)python logging现学现用 –

    python logging 模块

    logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点: 可以通过设置不同的日志等级,在release版本中只输出重要信息,而...

    python的logging模块.pdf

    详解python的日志模块logging和django中对logging模块的使用

    python 日志输出---logging浅析与使用

    python 日志输出---logging浅析与使用 详细的描述了python 中logging模块的使用方法,有具体的实例介绍,浅显易懂

    python改变日志(logging)存放位置的示例

    实现了简单版本的logging.config,支持一般的通过config文件进行配置。感觉还有更好的方法,是直接利用logging.config.fileConfig(log_config_file)方式读进来之后,通过修改handler方式来进行修改。 复制代码 代码...

    python日志输出----logging浅析与使用.pdf

    python日志输出----logging浅析与使用.pdf

    Python中内置的日志模块logging用法详解

    Python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志...

    Python常用模块logging——日志输出功能(示例代码)

    logging模块是Python的内置模块,主要用于输出运行日志,可以灵活配置输出日志的各项信息。这篇文章主要介绍了Python常用模块logging——日志输出的实例代码,需要的朋友可以参考下

    python日志输出----logging浅析与使用

    介绍python的logging模块用法,适合入门者。

    python logging日志模块以及多进程日志详解

    1. logging日志模块介绍 python的logging模块提供了灵活的标准模块,使得任何Python程序都可以使用这个第三方模块来实现日志记录。python logging 官方文档 logging框架中主要由四个部分组成: Loggers: 可供程序...

    python 日志 logging模块详细解析

    主要介绍了python 日志 logging模块 详细解析,本文通过实例代码给大家介绍的非常详细,对大家的工作或学习具有一定的参考借鉴价值,需要的朋友可以参考下

    Python中logger日志模块详解

    logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点: 可以通过设置不同的日志等级,在release版本中只输出重要信息,而...

    python日志logging工具类

    一个完美控制日志输出的工具类

    浅谈python日志的配置文件路径问题

    利用以上python代码配置日志输出时,如果该脚本是主脚本(即import别人,不被别人import,在执行逻辑的最顶端),path表示的日志配置文件只能与该脚本在同一目录下或者在其子文件夹里。 import sys sys.path.append...

    详解Python中logging日志模块在多进程环境下的使用

    许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行...这篇文章给大家主要介绍了在Python中logging日志模块在多进程环境下的使用,需要的朋友可以参考借鉴,下面来一起看看吧。

    python日志logging模块使用方法分析

    本文实例讲述了python日志logging模块使用方法。分享给大家供大家参考,具体如下: 一、从一个使用场景开始 开发一个日志系统, 既要把日志输出到控制台, 还要写入日志文件 import logging # 创建一个logger ...

    [python]-日志记录之logging(csdn)————程序.pdf

    [python]-日志记录之logging(csdn)————程序

    python日志输出----logging浅析与使用[参照].pdf

    python日志输出----logging浅析与使用[参照].pdf

Global site tag (gtag.js) - Google Analytics