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

yipeiwu_com5年前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数据类型判断及列表脚本操作

浅谈Python数据类型判断及列表脚本操作

数据类型判断 在python(版本3.0以上)使用变量,并进行值比较时。有时候会出现以下错误: TypeError: unorderable types: NoneType() <...

python取余运算符知识点详解

python取余运算符是什么? python取余运算符是%,即表示取模,返回除法的余数。 假设变量: a=10,b=20: 那么b % a 输出结果 0 注: Python语言支持以下类...

基于Python和PyYAML读取yaml配置文件数据

基于Python和PyYAML读取yaml配置文件数据

一、首先我们需要安装 PyYAML 第三方库 直接使用 pip install PyYAML 就可以(这里我之前是装过的,所以提示我PyYAML已经在这个目录下了,是5.1.2版本的)...

python 简单照相机调用系统摄像头实现方法 pygame

python 简单照相机调用系统摄像头实现方法 pygame

如下所示: # -*- coding: utf-8 -*- from VideoCapture import Device import time import pyg...

从numpy数组中取出满足条件的元素示例

例如问题:从 arr 数组中提取所有奇数元素。 input:arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) output: #>...