Python日志logging模塊功能與用法詳解
本文實(shí)例講述了Python日志logging模塊功能與用法。分享給大家供大家參考,具體如下:
本文內(nèi)容: logging模塊的介紹 logging模塊的基礎(chǔ)使用 logging模塊的擴(kuò)展使用 logging中的Filter 使用配置文件配置logging和logger 小技巧 想要了解更多?不如看看官方文檔。首發(fā)日期:2018-07-05
logging模塊的介紹: 它是一個(gè)python標(biāo)準(zhǔn)庫(kù),所以它的通用性很高,所有的python模塊都可以與它合作參與日志記錄。日志級(jí)別: 基本 中文意義 觸發(fā)情況 DEBUG 調(diào)試 調(diào)試時(shí)期 INFO 提示 正常運(yùn)行時(shí) WARINING 警告 現(xiàn)在可運(yùn)行,但未來(lái)可能發(fā)生錯(cuò)誤時(shí)(例如未來(lái)存儲(chǔ)空間可能不足) ERROR 錯(cuò)誤 當(dāng)程序發(fā)生錯(cuò)誤,無(wú)法執(zhí)行某些功能時(shí) CRITICAL 嚴(yán)重的、致命的 當(dāng)程序發(fā)生嚴(yán)重錯(cuò)誤,無(wú)法繼續(xù)運(yùn)行時(shí)默認(rèn)是WARNING。
這個(gè)表述可能不是很清晰,但意義類似程序報(bào)錯(cuò)信息,(假如)普通的異常信息只有一個(gè)報(bào)錯(cuò)原因,(那么為了方便觀看)可能還需要一些如錯(cuò)誤地點(diǎn),錯(cuò)誤事件等信息,而這些附加的統(tǒng)一的時(shí)間不應(yīng)該由生產(chǎn)錯(cuò)誤信息的部分來(lái)添加(可能有很多個(gè)模塊),而應(yīng)該將這個(gè)信息給專門做這事的部分來(lái)處理(交個(gè)formatter來(lái)處理)。
1.支持普通字符串%格式化,例如:
logging.info(’Started %s’%tag)
2.支持普通字符串format格式化,例如:
logging.info(’{} started ’.format(tag))
3.logging自帶的,例如:
logging.info(’%s start in’, tag) logging.info(’%s start in %s’,tag,address)format設(shè)置方法: 常用特殊字符: message是日志信息 levelname日志信息等級(jí) asctime是字符串形式的日期時(shí)間 name是logger的名字 levelno是數(shù)字形式的日志信息等級(jí) module是調(diào)用日志輸出函數(shù)的模塊名 funcName是調(diào)用日志輸出函數(shù)的函數(shù)名 lineno是調(diào)用日志輸出函數(shù)的代碼行數(shù)
根據(jù)不同的style,可以使用%(message)s或{message}或$message類似的格式來(lái)標(biāo)注指定位置使用指定信息來(lái)取代。
默認(rèn)格式: asctime 使用%(asctime)s funcName使用%(funcName)s levelname使用%(levelname)s message使用%(message)s lineno使用%(lineno)d module使用%(module)s name使用%(name)s官方文檔:
https://docs.python.org/3.6/library/logging.html
datefmt日期輸出格式的設(shè)置方法:設(shè)置format中特殊字符asctime(日期時(shí)間)的輸出格式
特殊字符: %y 兩位數(shù)的年份表示(00-99) %Y 四位數(shù)的年份表示(000-9999) %m 月份(01-12) %d 月內(nèi)中的一天(0-31) %H 24小時(shí)制小時(shí)數(shù)(0-23) %I 12小時(shí)制小時(shí)數(shù)(01-12) %M 分鐘數(shù)(00=59) %S 秒(00-59)使用自己想要的分隔符和順序來(lái)定義日期時(shí)間的格式,例如:
datefmt=’%m/%d/%Y %I:%M:%S %p’
使用小例子:不使用format的:
importlogging def show(): print('wechat running...') return 'wechat' def main(): logging.basicConfig(filename=’myapp.log’, level=logging.INFO) tag=show() logging.info(’Started %s’%tag) logging.info(’Finished %s’%tag) if __name__ == ’__main__’: main()
使用format和datefmt的:
importlogging def show(): print('wechat running...') return 'wechat' def main(): logging.basicConfig(filename=’myapp.log’, format=’%(asctime)s %(message)s’, datefmt=’%m/%d/%Y %I:%M:%S %p’,level=logging.INFO) tag=show() logging.info(’%s start in’, tag) logging.info(’%s Finished’,tag) if __name__ == ’__main__’: main()
PS:雖然上面沒有說(shuō)到logger對(duì)象,handler對(duì)象(默認(rèn)方向是標(biāo)準(zhǔn)輸出流),formatter對(duì)象,但實(shí)際上,它是有默認(rèn)的。不要因?yàn)槟J(rèn)值而搞錯(cuò)。所以不建議混雜基礎(chǔ)版的和擴(kuò)展版的使用。
logging模塊的擴(kuò)展使用:1.導(dǎo)入模塊:import logging2.獲取logger對(duì)象:
logger = logging.getLogger('AppName')
【這里根據(jù)不同的名字定義不同的logger對(duì)象,默認(rèn)為root?!?/p>
在模塊中使用時(shí),官方文檔中有一個(gè)這樣的代碼,有點(diǎn)意思:
logger = logging.getLogger(__name__)3.設(shè)置最低日志輸出級(jí)別:
logger.setlevel()
例如:
logger.setLevel(logging.INFO)4.創(chuàng)建并綁定handler:
handler用于處理日志信息的輸出方向,可以添加多個(gè)handler,代表同時(shí)向多個(gè)方向輸出信息
創(chuàng)建handler:輸出方向?yàn)槲募?,使用FileHandler,例如:
logging.FileHandler('test.log')
輸出方向?yàn)榱鳎褂肧treamHandler,例如:
logging.StreamHandler(sys.stdout)
PS:想了解更多Handler,可以自己查看官方文檔https://docs.python.org/3.6/howto/logging.html
綁定handler,使用addHandler():例如:
logger.addHandler(handler) 綁定后如果想解綁handler,使用removeHandler():
例如:
logger.removeHandler(handler)
5.定義handler的輸出格式formatter并綁定到handler上,formatter的設(shè)置方法類似上面基礎(chǔ)使用中的format:
創(chuàng)建:例如:
formatter = logging.Formatter(’%(asctime)s %(levelname)s: %(message)s’) 綁定:
handler.setFormatter(formatter) 或handler.formatter=formatter
6.將handle綁定到logger對(duì)象上。
logger.addHandler(file_handler)logger.addHandler(console_handler)
7.輸出日志:
調(diào)試級(jí)別: logger.debug(信息)
提示級(jí)別: logger.info(信息)
警告級(jí)別: logger.warn(信息)
錯(cuò)誤級(jí)別:
logger.error(信息)
logger.exception(信息)【與error不同的是,還附帶堆棧信息,一般用在發(fā)生異常時(shí)】
嚴(yán)重級(jí)別:
logger.fatal(信息) 【fatal是critical的別名】
logger.critical(信息)
使用示例:importlogging def demo(): #獲取logger對(duì)象 logger=logging.getLogger('WeChat') #設(shè)置日志等級(jí) logger.setLevel(logging.DEBUG) #創(chuàng)建綁定handler handler=logging.FileHandler(’wechat.log’) logger.addHandler(handler) # 創(chuàng)建綁定formatter formatter = logging.Formatter(’%(asctime)s %(levelname)s: %(message)s’) formatter.datefmt = ’%m/%d/%Y %I:%M:%S %p’ #可選的 handler.setFormatter(formatter) #嘗試輸出錯(cuò)誤信息 logger.debug('debug message') logger.info('info message') logger.warning('warining message') logger.error('error message') logger.critical('critical message') if __name__=='__main__': demo()補(bǔ)充: 如果你不想新建handler和formatter,可以使用basicConfig方式(可以使用basicConfig來(lái)配置所有的logger對(duì)象的handler和formatter),當(dāng)要注意混雜風(fēng)險(xiǎn)。【basicConfig和handler必須至少存在一個(gè),因?yàn)槟J(rèn)的logger對(duì)象也是需要初始化的】 logging模塊中還有一個(gè)filter,由于它涉及的內(nèi)容較多,單獨(dú)列在下面講。logging中的Filter: Filter用來(lái)過濾日志信息,例如你想輸出A類信息,但不想輸出C類信息,就可以進(jìn)行過濾 而由于所有的信息都有經(jīng)過過濾器,也可以使用過濾器來(lái)增加一些信息。
使用方法1:建立子類
下面的例子可能不是很符合應(yīng)用,僅用于舉例:
過濾非允許用戶的日志信息:
importlogging import sys class ContextFilter(logging.Filter): def filter(self, record): if record.role=='admin' : return True else: return False if __name__ == ’__main__’: logger=logging.getLogger('Wechat') logger.setLevel(logging.DEBUG) handler=logging.StreamHandler(sys.stdout) formatter=logging.Formatter(’%(asctime)s %(levelname)s: %(message)s Role: %(role)s’) handler.setFormatter(formatter) logger.addHandler(handler) #創(chuàng)建綁定fiter f = ContextFilter() logger.addFilter(f) logger.info(’An info message with %s’, ’some parameters’,extra={'role':'admin'}) logger.info(’An info message with %s’, ’some parameters’,extra={'role':'hacker'})#hacker的被過濾掉了
官網(wǎng)版的加信息版本:
importlogging from random import choice class ContextFilter(logging.Filter): ''' This is a filter which injects contextual information into the log. Rather than use actual contextual information, we just use random data in this demo. ''' USERS = [’jim’, ’fred’, ’sheila’] IPS = [’123.231.231.123’, ’127.0.0.1’, ’192.168.0.1’] def filter(self, record): record.ip = choice(ContextFilter.IPS) record.user = choice(ContextFilter.USERS) return True if __name__ == ’__main__’: levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) logging.basicConfig(level=logging.DEBUG, format=’%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s’) a1 = logging.getLogger(’a.b.c’) a2 = logging.getLogger(’d.e.f’) f = ContextFilter() a1.addFilter(f) a2.addFilter(f) a1.debug(’A debug message’) a1.info(’An info message with %s’, ’some parameters’) for x in range(10): lvl = choice(levels) lvlname = logging.getLevelName(lvl) a2.log(lvl, ’A message at %s level with %d %s’, lvlname, 2, ’parameters’)
使用方法2:使用filter函數(shù)
python3.2后,可以使用filter函數(shù)來(lái)做到上面方法1的效果
例子1:
importlogging import sys def myfilter(record): if record.role == 'admin': return True else: return False if __name__ == ’__main__’: logger=logging.getLogger('Wechat') logger.setLevel(logging.DEBUG) handler=logging.StreamHandler(sys.stdout) formatter=logging.Formatter(’%(asctime)s %(levelname)s: %(message)s Role: %(role)s’) handler.setFormatter(formatter) logger.addHandler(handler) #創(chuàng)建綁定fiter f = logging.Filter() f.filter=myfilter logger.addFilter(f) logger.info(’An info message with %s’, ’some parameters’,extra={'role':'admin'}) logger.info(’An info message with %s’, ’some parameters’,extra={'role':'hacker'})#hacker的被過濾掉了
例子2,利用lambda:
logger=logging.getLogger('Wechat') logger.setLevel(logging.DEBUG) handler=logging.StreamHandler(sys.stdout) formatter=logging.Formatter(’%(asctime)s %(levelname)s: %(message)s Role: %(role)s’) handler.setFormatter(formatter) logger.addHandler(handler) #創(chuàng)建綁定fiter#f = ContextFilter() f = logging.Filter() f.filter=lambda record: record.role=='admin'logger.addFilter(f)logger.info(’An info message with %s’, ’some parameters’,extra={'role':'admin'}) logger.info(’An info message with %s’, ’some parameters’,extra={'role':'hacker'})#hacker的被過濾掉了使用配置文件配置logger對(duì)象:
注意:logging默認(rèn)使用的logger對(duì)象叫做root
config文件配置方式:
importlogging import logging.config logging.config.fileConfig(’logging.conf’) # create logger logger = logging.getLogger(’simpleExample’) # ’application’ code logger.debug(’debug message’) logger.info(’info message’) logger.warn(’warn message’) logger.error(’error message’) logger.critical(’critical message’)
文件內(nèi)容:
[loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt=
PS:也支持YAML方式,這里不講述
小技巧:如果留意到過濾器例子的話,你可以發(fā)現(xiàn)
在formatter內(nèi)可以附加參數(shù):輸出信息時(shí),附加一個(gè)參數(shù)extra,附加的參數(shù)可以被formatter使用
importlogging import sys class ContextFilter(logging.Filter): def filter(self, record): if record.role=='admin' : return True else: return False if __name__ == ’__main__’: logger=logging.getLogger('Wechat') logger.setLevel(logging.DEBUG) handler=logging.StreamHandler(sys.stdout) formatter=logging.Formatter(’%(asctime)s %(levelname)s: %(message)s Role: %(role)s’) handler.setFormatter(formatter) logger.addHandler(handler) #創(chuàng)建綁定fiter f = ContextFilter() logger.addFilter(f) logger.info(’An info message with %s’, ’some parameters’,extra={'role':'admin'}) logger.info(’An info message with %s’, ’some parameters’,extra={'role':'hacker'})#hacker的被過濾掉了想要了解更多?不如看看官方文檔。
https://docs.python.org/3.6/library/logging.html
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python日志操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. xml中的空格之完全解說(shuō)4. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問題……5. XML入門的常見問題(四)6. php bugs代碼審計(jì)基礎(chǔ)詳解7. ASP使用MySQL數(shù)據(jù)庫(kù)的方法8. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享9. WMLScript的語(yǔ)法基礎(chǔ)10. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法
