1. 程式人生 > >Python:日誌模組logging的應用

Python:日誌模組logging的應用



  通常,在商用軟體中均會有完整的日誌機制,之前使用C語言實現過一個《簡單的分級別寫日誌程式》具有以下功能和不足:

在Python中,上面以實現的和已經實現的,均可以使用logging模組迅速搞定,且僅僅只需要一個配置檔案,兩行程式碼,實現過程如下(僅以輸出的磁碟檔案為例,命令輸出只需要修改配置檔案即可,具體可查API手冊):

1. 定義配置檔案logging.conf:

[loggers]  
keys=root,applog  
[handlers]  
keys=rotateFileHandler  
[formatters]  
keys=applog_format  
  
[formatter_applog_format]  
format=[%(asctime)s - %(name)s]%(levelname)s:  %(message)s - %(filename)s:%(lineno)d  
  
[logger_root]  
level=NOTSET  
handlers=rotateFileHandler  
  
[logger_applog]  
level=NOTSET  
handlers=rotateFileHandler  
qualname=simple_example  
  
[handler_rotateFileHandler]  
class=handlers.RotatingFileHandler  
level=NOTSET  
formatter=applog_format  
args=('log_1.log', 'a', 10000, 9) 

注意前三個[ ]中的keys,這個在後面各[ ]中定義定義,section的取名格式如looger_自定義名稱, handler_自定義名稱,我偷懶直接使用了標準名稱,其他一樣,最後一個要注意的就是format,即日誌檔案中內容的格式,具體見後面附一。level引數是日誌級別,可擴充套件,如果使用python自己的,有以下四個級別:

Level Numeric value   
CRITICAL       50   
ERROR          40   
WARNING        30   
INFO           20   
DEBUG          10   
NOTSET          0  


例如配置檔案中level定義為WARN,則INFO, DEBUG,NOTSET三個級別的日誌點則不會輸出,很方便的做到了日誌級別控制。

args定義了日誌方件名,寫方式,最大大小,儲存最多個數等屬性。

2.編碼,測試

#!/usr/bin/env python  
# -*- coding: utf-8 -*-  
  
import logging  
import logging.config  
  
#日誌初始化  
LOG_FILENAME = 'logging.conf'  
logging.config.fileConfig(LOG_FILENAME)  
logger = logging.getLogger("simple_log_example")  
  
#測試程式碼  
logger.debug("debug message")  
logger.info("info message")  
logger.warn("warn message")  
logger.error("error message")  
logger.critical("critical message")  

執行後,檢視日誌檔案,內容如下:

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

如將日誌級別設定為WARN,再次執行,檢視日誌:

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

附一:format引數格式說明:

Format Description  
%(name)s Name of the logger (logging channel).  
%(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).  
%(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.