本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python日志操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。