首页 > 编程 > Python > 正文

Python使用修饰器进行异常日志记录操作示例

2019-11-25 13:08:13
字体:
来源:转载
供稿:网友

本文实例讲述了Python使用修饰器进行异常日志记录操作。分享给大家供大家参考,具体如下:

当脚本中需要进行的的相同的异常操作很多的时候,可以用修饰器来简化代码。比如我需要记录抛出的异常:

在log_exception.py文件中,

import functoolsimport loggingdef 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 loggerdef 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_exceptiondef reciprocal(x):  return 1/xif __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程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表