python-log

參考:http://blog.chinaunix.net/uid-14833587-id-76529.html

Log信息不同於使用打樁法打印一定的標記信息,log可以根據程序需要而分出不同的log級別,比如info、debug、warn等等級別的信息,只要實時控制log級別開關就可以爲開發人員提供更好的log信息,與log4xx類似,logger,handler和日誌消息的調用可以有具體的日誌級別(Level),只有在日誌消息的級別大於logger和handler的設定的級別,纔會顯示。下面我就來談談我在Python中使用的logging模塊一些方法。

logging模塊介紹

Python的logging模塊提供了通用的日誌系統,熟練使用logging模塊可以方便開發者開發第三方模塊或者是自己的Python應用。同樣這個模塊提供不同的日誌級別,並可以採用不同的方式記錄日誌,比如文件,HTTP、GET/POST,SMTP,Socket等,甚至可以自己實現具體的日誌記錄方式。下文我將主要介紹如何使用文件方式記錄log。

logging模塊包括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的構造方法需要兩個參數:消息的格式字符串和日期字符串,這兩個參數都是可選的。

基本使用方法

一些小型的程序我們不需要構造太複雜的log系統,可以直接使用logging模塊的basicConfig函數即可,代碼如下:


'''
Created on 2012-8-12
 
@author: walfred
@module: loggingmodule.BasicLogger
'''
import logging
 
log_file = "./basic_logger.log"
 
logging.basicConfig(filename = log_file, level = logging.DEBUG)
 
logging.debug("this is a debugmsg!")
logging.info("this is a infomsg!")
logging.warn("this is a warn msg!")
logging.error("this is a error msg!")
logging.critical("this is a critical msg!")


運行程序時我們就會在該文件的當前目錄下發現basic_logger.log文件,查看basic_logger.log內容如下:

INFO:root:this is a info msg!
DEBUG:root:this is a debug msg!
WARNING:root:this is a warn msg!
ERROR:root:this is a error msg!
CRITICAL:root:this is a critical msg!



需要說明的是我將level設定爲DEBUG級別,所以log日誌中只顯示了包含該級別及該級別以上的log信息。信息級別依次是:notset、debug、info、warn、error、critical。如果在多個模塊中使用這個配置的話,只需在主模塊中配置即可,其他模塊會有相同的使用效果。



較高級版本

上述的基礎使用比較簡單,沒有顯示出logging模塊的厲害,適合小程序用,現在我介紹一個較高級版本的代碼,我們需要依次設置logger、handler、formatter等配置。



'''
Created on 2012-8-12
 
@author: walfred
@module: loggingmodule.NomalLogger
'''
import logging
 
log_file = "./nomal_logger.log"
log_level = logging.DEBUG
 
logger = logging.getLogger("loggingmodule.NomalLogger")
handler = logging.FileHandler(log_file)
formatter = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s")
 
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(log_level)
 
#test
logger.debug("this is a debug msg!")
logger.info("this is a info msg!")
logger.warn("this is a warn msg!")
logger.error("this is a error msg!")
logger.critical("this is a critical msg!")


這時我們查看當前目錄的nomal_logger.log日誌文件,如下:

[DEBUG][][2012-08-12 17:43:59,295]this is a debug msg!
[INFO][][2012-08-12 17:43:59,295]this is a info msg!
[WARNING][][2012-08-12 17:43:59,295]this is a warn msg!
[ERROR][][2012-08-12 17:43:59,295]this is a error msg!
[CRITICAL][][2012-08-12 17:43:59,295]this is a critical msg!



這個對照前面介紹的logging模塊,不難理解,下面的最終版本將會更加完整。


完善版本

這個最終版本我用singleton設計模式來寫一個Logger類,代碼如下:


'''
Created on 2012-8-12
 
@author: walfred
@module: loggingmodule.FinalLogger
'''
 
import logging.handlers
 
class FinalLogger:
 
 logger = None
 
 levels = {"n" : logging.NOTSET,
  "d" : logging.DEBUG,
  "i" : logging.INFO,
  "w" : logging.WARN,
  "e" : logging.ERROR,
  "c" : logging.CRITICAL}
 
 log_level = "d"
 log_file = "final_logger.log"
 log_max_byte = 10 * 1024 * 1024;
 log_backup_count = 5
 
 @staticmethod
 def getLogger():
  if FinalLogger.logger is not None:
   return FinalLogger.logger
 
  FinalLogger.logger = logging.Logger("oggingmodule.FinalLogger")
  log_handler = logging.handlers.RotatingFileHandler(filename = FinalLogger.log_file,\
  maxBytes = FinalLogger.log_max_byte,\
  backupCount = FinalLogger.log_backup_count)
  log_fmt = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s")
  log_handler.setFormatter(log_fmt)
  FinalLogger.logger.addHandler(log_handler)
  FinalLogger.logger.setLevel(FinalLogger.levels.get(FinalLogger.log_level))
  return FinalLogger.logger
 
if __name__ == "__main__":
 logger = FinalLogger.getLogger()
 logger.debug("this is a debug msg!")
 logger.info("this is a info msg!")
 logger.warn("this is a warn msg!")
 logger.error("this is a error msg!")
 logger.critical("this is a critical msg!")







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章