python中 logging的使用詳解
日志是用來記錄程序在運行過程中發(fā)生的狀況,在程序開發(fā)過程中添加日志模塊能夠幫助我們了解程序運行過程中發(fā)生了哪些事件,這些事件也有輕重之分。
根據(jù)事件的輕重可分為以下幾個級別:
DEBUG: 詳細信息,通常僅在診斷問題時才受到關(guān)注。整數(shù)level=10
INFO: 確認程序按預(yù)期工作。整數(shù)level=20
WARNING:出現(xiàn)了異常,但是不影響正常工作.整數(shù)level=30
ERROR:由于某些原因,程序 不能執(zhí)行某些功能。整數(shù)level=40
CRITICAL:嚴重的錯誤,導(dǎo)致程序不能運行。整數(shù)level=50
默認的級別是WARNING,也就意味著只有級別大于等于的才會被看到,跟蹤日志的方式可以是寫入到文件中,也可以直接輸出到控制臺。
輸出到控制臺
下面是一個小例子通過將日志輸出到控制臺的方法:
import logging
logging.warning('Watch out!') # 將輸出到控制臺
logging.info('I told you so') # 不會輸出
logging.error("an error occurrence!") #將輸出到控制臺
輸出結(jié)果
WARNING:root:Watch out! ERROR:root:an error occurrence
輸出到文件中
新開一個python解釋器,確保不是上面代碼的session
import logging
logging.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中的內(nèi)容
DEBUG:root:This message should go to the log file INFO:root:So should this WARNING:root:And this, too
假定需要手動調(diào)整日志的級別,我們可以在命令行以參數(shù)的形式傳入--log=INFO,在代碼中可以采用下面的處理方式
# 輸入?yún)?shù) --log=DEBUG or --log=debug
numeric_level = getattr(logging, loglevel.upper(), None)#返回10,否則None
if not isinstance(numeric_level, int):
raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level, ...)
變量的日志
使用格式化字符串的方式,為變量添加日志
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
自定義日志格式
我們還可以根據(jù)我們的需求自定義輸出模板
import logging
logging.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 console 2017-10-24 14:03:53,690: INFO: So should this 2017-10-24 14:03:53,694: WARNING: And this, too
內(nèi)部實際傳入的為一個字典,%(key)為字典的key。
上面是python logging模塊的一些基本用法, 已經(jīng)能夠滿足我們的許多需求,下面簡單介紹下logging的一些高級用法。在logging模塊中主要包括logger,handlers,filter,formatters,這幾個組件
logger:提供了應(yīng)用接口,供程序使用
handlers:用來將logger創(chuàng)建的log 發(fā)送到相應(yīng)的目的地
filter:為要輸出的日志提供了更細粒度的設(shè)置
formatters:設(shè)置最終的輸出格式
下面是這幾個組件配合使用的例子
import logging
logger = logging.getLogger('logger_name')# 創(chuàng)建logger對象
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()# 創(chuàng)建 console handler 并設(shè)置級別為debug
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# 創(chuàng)建輸出格式
handler.setFormatter(formatter)# 為handler添加fromatter
logger.addHandler(handler)# 將handler添加到 logger
logger.debug('debug message')# 'application' code
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
輸出結(jié)果:
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
小應(yīng)用案例
下面是自己定義的一個日志處理方法,既能夠?qū)懭氲轿募校L動保存近15天的日志,日志格式app.log, app.log.1, app.log.2),又能輸出到控制臺。
import logging
from logging.handlers import TimedRotatingFileHandler
class 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')
總結(jié)
以上所述是小編給大家介紹的python中 logging的使用詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
python 協(xié)程中的迭代器,生成器原理及應(yīng)用實例詳解
這篇文章主要介紹了python 協(xié)程中的迭代器,生成器原理及應(yīng)用,結(jié)合具體實例形式詳細分析了Python協(xié)程中的迭代器,生成器概念、原理及應(yīng)用操作技巧,需要的朋友可以參考下2019-10-10
關(guān)于Python中的向量相加和numpy中的向量相加效率對比
今天小編就為大家分享一篇關(guān)于Python中的向量相加和numpy中的向量相加效率對比,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python Request爬取seo.chinaz.com百度權(quán)重網(wǎng)站的查詢結(jié)果過程解析
這篇文章主要介紹了Request爬取網(wǎng)站(seo.chinaz.com)百度權(quán)重的查詢結(jié)果過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下2019-08-08
Python實現(xiàn)樸素貝葉斯的學(xué)習與分類過程解析
這篇文章主要介紹了Python實現(xiàn)樸素貝葉斯的學(xué)習與分類過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下2019-08-08
tensorflow1.0學(xué)習之模型的保存與恢復(fù)(Saver)
這篇文章主要介紹了tensorflow1.0學(xué)習之模型的保存與恢復(fù)(Saver) ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
Python常用模塊logging——日志輸出功能(示例代碼)
logging模塊是Python的內(nèi)置模塊,主要用于輸出運行日志,可以靈活配置輸出日志的各項信息。這篇文章主要介紹了Python常用模塊logging——日志輸出的實例代碼,需要的朋友可以參考下2019-11-11

