Python使用修飾器進行異常日志記錄操作示例
本文實例講述了Python使用修飾器進行異常日志記錄操作。分享給大家供大家參考,具體如下:
當腳本中需要進行的的相同的異常操作很多的時候,可以用修飾器來簡化代碼。比如我需要記錄拋出的異常:
在log_exception.py文件中,
import functools import logging def create_logger(): logger = logging.getLogger("test_log") logger.setLevel(logging.INFO) fh = logging.FileHandler("test.log") fmt = "[%(asctime)s-%(name)s-%(levelname)s]: %(message)s" formatter = logging.Formatter(fmt) fh.setFormatter(formatter) logger.addHandler(fh) return logger def log_exception(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): logger = create_logger() try: fn(*args, **kwargs) except Exception as e: logger.exception("[Error in {}] msg: {}".format(__name__, str(e))) raise return wrapper
在test.py文件中:
from log_exception import log_exception @log_exception def reciprocal(x): return 1/x if __name__ == "__main__": reciprocal(0)
在test.log文件中可以看到以下錯誤信息:
[2017-11-26 23:37:41,012-test_log-ERROR]: [Error in __main__] msg: integer division or modulo by zero
Traceback (most recent call last):
File "<ipython-input-43-cfa2d18586a3>", line 16, in wrapper
fn(*args, **kwargs)
File "<ipython-input-46-37aa8ff0ba48>", line 3, in reciprocal
return 1/x
ZeroDivisionError: integer division or modulo by zero
參考:
1. https://wiki.python.org/moin/PythonDecorators
2. https://www.blog.pythonlibrary.org/2016/06/09/python-how-to-create-an-exception-logging-decorator/
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python日志操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
使用Python爬蟲庫BeautifulSoup遍歷文檔樹并對標簽進行操作詳解
今天為大家介紹下Python爬蟲庫BeautifulSoup遍歷文檔樹并對標簽進行操作的詳細方法與函數(shù)2020-01-01python基礎(chǔ)教程之數(shù)字處理(math)模塊詳解
這篇文章主要介紹了pythonr的數(shù)字處理模塊知識(math),需要的朋友可以參考下2014-03-03pytorch 狀態(tài)字典:state_dict使用詳解
今天小編就為大家分享一篇pytorch 狀態(tài)字典:state_dict使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01Python實現(xiàn)多子圖繪制系統(tǒng)的示例詳解
這篇文章主要介紹了如何利用python實現(xiàn)多子圖繪制系統(tǒng),文中的示例代碼講解詳細,具有一定的的參考價值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-09-09