日志是用來記錄程序在運行過程中發生的狀況,在程序開發過程中添加日志模塊能夠幫助我們了解程序運行過程中發生了哪些事件,這些事件也有輕重之分。
根據事件的輕重可分為以下幾個級別:
DEBUG: 詳細信息,通常僅在診斷問題時才受到關注。整數level=10
INFO: 確認程序按預期工作。整數level=20
WARNING:出現了異常,但是不影響正常工作.整數level=30
ERROR:由于某些原因,程序 不能執行某些功能。整數level=40
CRITICAL:嚴重的錯誤,導致程序不能運行。整數level=50
默認的級別是WARNING,也就意味著只有級別大于等于的才會被看到,跟蹤日志的方式可以是寫入到文件中,也可以直接輸出到控制臺。
輸出到控制臺
下面是一個小例子通過將日志輸出到控制臺的方法:
import logginglogging.warning('Watch out!') # 將輸出到控制臺logging.info('I told you so') # 不會輸出logging.error("an error occurrence!") #將輸出到控制臺輸出結果
WARNING:root:Watch out!ERROR:root:an error occurrence
輸出到文件中
新開一個python解釋器,確保不是上面代碼的session
import logginglogging.basicConfig(filename='example.log',level=logging.DEBUG)logging.debug('This message should go to the log file')logging.info('So should this')logging.warning('And this, too')這個時候控制臺上面就沒有了輸出,文件example.log中的內容
DEBUG:root:This message should go to the log fileINFO:root:So should thisWARNING:root:And this, too
假定需要手動調整日志的級別,我們可以在命令行以參數的形式傳入--log=INFO,在代碼中可以采用下面的處理方式
# 輸入參數 --log=DEBUG or --log=debugnumeric_level = getattr(logging, loglevel.upper(), None)#返回10,否則Noneif not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % loglevel)logging.basicConfig(level=numeric_level, ...)變量的日志
使用格式化字符串的方式,為變量添加日志
import logginglogging.warning('%s before you %s', 'Look', 'leap!')自定義日志格式
我們還可以根據我們的需求自定義輸出模板
import logginglogging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s',level=logging.DEBUG)logging.debug('This message should appear on the console')logging.info('So should this')logging.warning('And this, too')輸出
2017-10-24 14:03:53,671: DEBUG: This message should appear on the console2017-10-24 14:03:53,690: INFO: So should this2017-10-24 14:03:53,694: WARNING: And this, too
內部實際傳入的為一個字典,%(key)為字典的key。
上面是python logging模塊的一些基本用法, 已經能夠滿足我們的許多需求,下面簡單介紹下logging的一些高級用法。在logging模塊中主要包括logger,handlers,filter,formatters,這幾個組件
logger:提供了應用接口,供程序使用
handlers:用來將logger創建的log 發送到相應的目的地
filter:為要輸出的日志提供了更細粒度的設置
formatters:設置最終的輸出格式
下面是這幾個組件配合使用的例子
import logginglogger = logging.getLogger('logger_name')# 創建logger對象logger.setLevel(logging.DEBUG)handler = logging.StreamHandler()# 創建 console handler 并設置級別為debughandler.setLevel(logging.DEBUG)formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# 創建輸出格式handler.setFormatter(formatter)# 為handler添加fromatterlogger.addHandler(handler)# 將handler添加到 loggerlogger.debug('debug message')# 'application' codelogger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message')輸出結果:
2017-10-24 16:50:43,127 - logger_name - DEBUG - debug message
2017-10-24 16:50:43,138 - logger_name - INFO - info message
2017-10-24 16:50:43,141 - logger_name - WARNING - warn message
2017-10-24 16:50:43,144 - logger_name - ERROR - error message
2017-10-24 16:50:43,148 - logger_name - CRITICAL - critical message
小應用案例
下面是自己定義的一個日志處理方法,既能夠寫入到文件中(滾動保存近15天的日志,日志格式app.log, app.log.1, app.log.2),又能輸出到控制臺。
import loggingfrom logging.handlers import TimedRotatingFileHandlerclass MylogHandler(logging.Logger): def __init__(self,name,level="DEBUG",stream=True,files=True): self.name = name self.level = level logging.Logger.__init__(self,self.name,level=self.level) if stream: self.__streamHandler__(self.level) if files: self.__filesHandler__(self.level) def __streamHandler__(self,level=None): handler = TimedRotatingFileHandler(filename=self.name+".log", when='D', interval=1, backupCount=15) handler.suffix = '%Y%m%d.log' handler.setLevel(level) formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') handler.setFormatter(formatter) self.addHandler(handler) #將hander添加到logger上 def __filesHandler__(self,level=None): handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') handler.setFormatter(formatter) handler.setLevel(level) self.addHandler(handler)if __name__ == '__main__': log = MylogHandler('test') log.info('this is a my log handler')總結
以上所述是小編給大家介紹的python中 logging的使用詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!
新聞熱點
疑難解答