歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python:日志模塊logging的應用

Python:日志模塊logging的應用

日期:2017/3/1 10:32:30   编辑:Linux編程
通常,在商用軟件中均會有完整的日志機制,之前使用C語言實現過一個《簡單的分級別寫日志程序》見 http://www.linuxidc.com/Linux/2012-02/54210.htm,具有以下功能和不足:

[cpp]
  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:

[plain]
  1. [loggers]
  2. keys=root,applog
  3. [handlers]
  4. keys=rotateFileHandler
  5. [formatters]
  6. keys=applog_format
  7. [formatter_applog_format]
  8. format=[%(asctime)s - %(name)s]%(levelname)s: %(message)s - %(filename)s:%(lineno)d
  9. [logger_root]
  10. level=NOTSET
  11. handlers=rotateFileHandler
  12. [logger_applog]
  13. level=NOTSET
  14. handlers=rotateFileHandler
  15. qualname=simple_example
  16. [handler_rotateFileHandler]
  17. class=handlers.RotatingFileHandler
  18. level=NOTSET
  19. formatter=applog_format
  20. args=('log_1.log', 'a', 10000, 9)
注意前三個[ ]中的keys,這個在後面各[ ]中定義定義,section的取名格式如looger_自定義名稱, handler_自定義名稱,我偷懶直接使用了標准名稱,其他一樣,最後一個要注意的就是format,即日志文件中內容的格式,具體見後面附一。level參數是日志級別,可擴展,如果使用python自己的,有以下四個級別:

[html]
  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.編碼,測試

[python]
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import logging
  4. import logging.config
  5. #日志初始化
  6. LOG_FILENAME = 'logging.conf'
  7. logging.config.fileConfig(LOG_FILENAME)
  8. logger = logging.getLogger("simple_log_example")
  9. #測試代碼
  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")
運行後,查看日志文件,內容如下:

[plain]
  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,再次運行,查看日志:

[plain]
  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參數格式說明:

[plain]
  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.
Copyright © Linux教程網 All Rights Reserved