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/
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python日志操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
通過python實現(xiàn)windows桌面截圖代碼實例
這篇文章主要介紹了python實現(xiàn)windows桌面截圖代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-01-01
Python3中關于cookie的創(chuàng)建與保存
今天小編就為大家分享一篇關于Python3中關于cookie的創(chuàng)建與保存的文章,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10
Python reshape的用法及多個二維數(shù)組合并為三維數(shù)組的實例
今天小編就為大家分享一篇Python reshape的用法及多個二維數(shù)組合并為三維數(shù)組的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
python實現(xiàn)文件+參數(shù)發(fā)送request的實例代碼
這篇文章主要介紹了python實現(xiàn)文件+參數(shù)發(fā)送request的實例代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01

