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

yipeiwu_com6年前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相关内容感兴趣的读者可查看本站专题:《Python日志操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

用python写的一个wordpress的采集程序

用python写的一个wordpress的采集程序

在学习python的过程中,经过不断的尝试及努力,终于完成了第一个像样的python程序,虽然还有很多需要优化的地方,但是目前基本上实现了我所要求的功能,先贴一下程序代码: 具体代码如...

Python中max函数用于二维列表的实例

最近写一个和二维列表有关的算法时候发现的 当用max求二维列表中最大值时,输出的结果是子列表首元素最大的那个列表 测试如下 c=[[1,2,-1],[0,5,6]] a=[[0,3...

python 魔法函数实例及解析

python的几个魔法函数 __repr__ Python中这个__repr__函数,对应repr(object)这个函数,返回一个可以用来表示对象的可打印字符串.如果我们直接打印...

Python 加密的实例详解

 Python 加密的实例详解 hashlib支持md5,sha1,sha256,sha384,sha512,用法和md5一样  import hashlib...

Python切片用法实例教程

本文以实例形式讲述了Python中切片操作的用法,分享给大家供大家参考借鉴,具体如下: 取一个list或tuple的部分元素是非常常见的操作。比如,一个list如下: >>...