Python使用logging結(jié)合decorator模式實(shí)現(xiàn)優(yōu)化日志輸出的方法
本文實(shí)例講述了Python使用logging結(jié)合decorator模式實(shí)現(xiàn)優(yōu)化日志輸出的方法。分享給大家供大家參考,具體如下:
python內(nèi)置的loging模塊非常簡便易用, 很適合程序運(yùn)行日志的輸出。
而結(jié)合python的裝飾器模式,則可實(shí)現(xiàn)簡明實(shí)用的代碼。測試代碼如下所示:
#! /usr/bin/env python2.7 # -*- encoding: utf-8 -*- import logging logging.basicConfig(format='[%(asctime)s] %(message)s', level=logging.INFO) def time_recorder(func): """裝飾器, 用在func方法執(zhí)行前后, 增加運(yùn)行信息""" def wrapper(): logging.info("Begin to execute function: %s" % func.__name__) func() logging.info("Finish executing function: %s" % func.__name__) return wrapper @time_recorder def first_func(): print "I'm first_function. I'm doing something..." @time_recorder def second_func(): print "I'm second_function. I'm doing something..." if __name__ == "__main__": first_func() second_func()
運(yùn)行并得到輸出:
[2014-04-01 18:02:13,724] Begin to execute function: first_func I'm first_function. I'm doing something... [2014-04-01 18:02:13,725] Finish executing function: first_func [2014-04-01 18:02:13,725] Begin to execute function: second_func I'm second_function. I'm doing something... [2014-04-01 18:02:13,725] Finish executing function: second_func
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- Python內(nèi)置模塊logging用法實(shí)例分析
- 詳解Python自建logging模塊
- Python logging管理不同級(jí)別log打印和存儲(chǔ)實(shí)例
- python使用logging模塊發(fā)送郵件代碼示例
- python logging日志模塊的詳解
- python中 logging的使用詳解
- python中l(wèi)ogging庫的使用總結(jié)
- python中日志logging模塊的性能及多進(jìn)程詳解
- 詳解使用python的logging模塊在stdout輸出的兩種方法
- 詳解Python中l(wèi)ogging日志模塊在多進(jìn)程環(huán)境下的使用
- python logging 日志輪轉(zhuǎn)文件不刪除問題的解決方法
- Python中內(nèi)置的日志模塊logging用法詳解
- python中l(wèi)ogging包的使用總結(jié)
相關(guān)文章
python語言線程標(biāo)準(zhǔn)庫threading.local解讀總結(jié)
在本篇文章里我們給各位整理了一篇關(guān)于python threading.local源碼解讀的相關(guān)文章知識(shí)點(diǎn),有需要的朋友們可以學(xué)習(xí)下。2019-11-11Python動(dòng)態(tài)演示旋轉(zhuǎn)矩陣的作用詳解
一個(gè)矩陣我們想讓它通過編程,實(shí)現(xiàn)各種花樣的變化怎么辦呢?下面這篇文章主要給大家介紹了關(guān)于Python動(dòng)態(tài)演示旋轉(zhuǎn)矩陣的作用,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12Python入門教程(二十二)Python的類和對(duì)象
這篇文章主要介紹了Python入門教程(二十二)Python的類和對(duì)象,Python是一門非常強(qiáng)大好用的語言,也有著易上手的特性,本文為入門教程,需要的朋友可以參考下2023-04-04python基礎(chǔ)編程小實(shí)例之計(jì)算圓的面積
Python是最常用的編程語言,這種語言就是一種可以快速開發(fā)應(yīng)用的解釋型語言,有些用戶不知道該怎么在Python編程里計(jì)算圓的面積,現(xiàn)在就給大家具體解釋一下,下面這篇文章主要給大家介紹了關(guān)于python基礎(chǔ)編程小實(shí)例之計(jì)算圓的面積的相關(guān)資料,需要的朋友可以參考下2023-03-03使用python將請求的requests headers參數(shù)格式化方法
今天小編就為大家分享一篇使用python將請求的requests headers參數(shù)格式化方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01