[Python]日志模块logging的应用

http://blog.csdn.net/dyx1024/article/details/7250828

通常,在商用软件中均会有完整的日志机制,之前使用C语言实现过一个《简单的分级别写日志程序》,具有以下功能和不足:

  1. /************************************************************************/    
  2.   * 摘    要:此文件实现了普通WINDOWS程序中的日志功能   
  3.   *           主要有以下特点:   
  4.   *           1. 根据日期创建日志文件目录,每天的日志分别存放在不同的日志目录中;   
  5.   *           2. 日志内容分三种类型,根据不同需要,写不同的日志类型的日志文件,   
  6.   *              方便通过日志定位、分析问题;   
  7.   *           3. 函数经过比较好的封装,便于复用;   
  8.   *           待改进点:   
  9.   *           1. 为了方便,日志内容打印时使用了time函数,其精确度较低;   
  10.   *           2. 可将这些函数封装为一个日志类,或者动态库,使其更通用;   
  11.   *           3. 没有考虑跨平台情景,目前只使用于WINDOWS下   
  12.   *           4. 日志文件内容还可进一步改进,比如打印出当前文件名与行号,使用日志功能   
  13.   *              更加实用;   
  14.   *   
  15.   * 当前版本:1.0   
  16.   * 作    者:duanyongxing    
  17.   * 完成日期:2009年10月11日                                                                    
  18. /************************************************************************/   

  在Python中,上面以实现的和已经实现的,均可以使用logging模块迅速搞定,且仅仅只需要一个配置文件,两行代码,实现过程如下(仅以输出的磁盘文件为例,命令输出只需要修改配置文件即可,具体可查API手册):

1. 定义配置文件logging.conf:

  1. [loggers]  
  2. keys=root,applog  
  3. [handlers]  
  4. keys=rotateFileHandler  
  5. [formatters]  
  6. keys=applog_format  
  7.   
  8. [formatter_applog_format]  
  9. format=[%(asctime)s - %(name)s]%(levelname)s:  %(message)s - %(filename)s:%(lineno)d  
  10.   
  11. [logger_root]  
  12. level=NOTSET  
  13. handlers=rotateFileHandler  
  14.   
  15. [logger_applog]  
  16. level=NOTSET  
  17. handlers=rotateFileHandler  
  18. qualname=simple_example  
  19.   
  20. [handler_rotateFileHandler]  
  21. class=handlers.RotatingFileHandler  
  22. level=NOTSET  
  23. formatter=applog_format  
  24. args=('log_1.log', 'a', 10000, 9)  


注意前三个[ ]中的keys,这个在后面各[ ]中定义定义,section的取名格式如looger_自定义名称, handler_自定义名称,我偷懒直接使用了标准名称,其他一样,最后一个要注意的就是format,即日志文件中内容的格式,具体见后面附一。 level参数是日志级别,可扩展,如果使用python自己的,有以下四个级别:

  1. Level Numeric value   
  2. CRITICAL       50   
  3. ERROR          40   
  4. WARNING        30   
  5. INFO           20   
  6. DEBUG          10   
  7. NOTSET          0   

例如配置文件中level定义为WARN,则INFO, DEBUG,NOTSET三个级别的日志点则不会输出,很方便的做到了日志级别控制。

args定义了日志方件名,写方式,最大大小,保存最多个数等属性。


2.编码,测试

  1. #!/usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3.   
  4. import logging  
  5. import logging.config  
  6.   
  7. #日志初始化  
  8. LOG_FILENAME = 'logging.conf'  
  9. logging.config.fileConfig(LOG_FILENAME)  
  10. logger = logging.getLogger("simple_log_example")  
  11.   
  12. #测试代码  
  13. logger.debug("debug message")  
  14. logger.info("info message")  
  15. logger.warn("warn message")  
  16. logger.error("error message")  
  17. logger.critical("critical message")  


运行后,查看日志文件,内容如下:

  1. [2012-02-11 14:47:05,483 - simple_log_example]DEBUG:  debug message - test_log.py:48  
  2. [2012-02-11 14:47:05,483 - simple_log_example]INFO:  info message - test_log.py:49  
  3. [2012-02-11 14:47:05,483 - simple_log_example]WARNING:  warn message - test_log.py:50  
  4. [2012-02-11 14:47:05,483 - simple_log_example]ERROR:  error message - test_log.py:51  
  5. [2012-02-11 14:47:05,483 - simple_log_example]CRITICAL:  critical message - test_log.py:52  


如将日志级别设置为WARN,再次运行,查看日志:

  1. [2012-02-11 14:54:20,046 - simple_log_example]WARNING:  warn message - test_log.py:50  
  2. [2012-02-11 14:54:20,092 - simple_log_example]ERROR:  error message - test_log.py:51  
  3. [2012-02-11 14:54:20,092 - simple_log_example]CRITICAL:  critical message - test_log.py:52  



附一:format参数格式说明:

    1. Format Description   
    2. %(name)s Name of the logger (logging channel).   
    3. %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).   
    4. %(levelname)s Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').   
    5. %(pathname)s Full pathname of the source file where the logging call was issued (if available).   
    6. %(filename)s Filename portion of pathname.   
    7. %(module)s Module (name portion of filename).   
    8. %(funcName)s Name of function containing the logging call.   
    9. %(lineno)d Source line number where the logging call was issued (if available).   
    10. %(created)f Time when the LogRecord was created (as returned by time.time()).   
    11. %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.   
    12. %(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).   
    13. %(msecs)d Millisecond portion of the time when the LogRecord was created.   
    14. %(thread)d Thread ID (if available).   
    15. %(threadName)s Thread name (if available).   
    16. %(process)d Process ID (if available).   
    17. %(message)s The logged message, computed as msg % args.  
原文地址:https://www.cnblogs.com/androidme/p/3038649.html