|
| 1 | +#+TITLE: 如何创建记录异常日志的装饰器 |
| 2 | +#+URL: http://www.blog.pythonlibrary.org/2016/06/09/python-how-to-create-an-exception-logging-decorator/ |
| 3 | +#+AUTHOR: lujun9972 |
| 4 | +#+CATEGORY: Python Common |
| 5 | +#+DATE: [2016-06-10 五 15:41] |
| 6 | +#+OPTIONS: ^:{} |
| 7 | + |
| 8 | +有一天,我突然想要创建一个用于捕获并记录一场的装饰器. 我在[[https://gist.github.com/diosmosis/1148066][Github]] 上发现一个颇为复杂的例子,该例子启发了我,并让我写下了以下代码: |
| 9 | +#+BEGIN_SRC python |
| 10 | + # exception_decor.py |
| 11 | + import logging |
| 12 | + |
| 13 | + def create_logger(): |
| 14 | + """ |
| 15 | + Creates a logging object and returns it |
| 16 | + """ |
| 17 | + logger = logging.getLogger("example_logger") |
| 18 | + logger.setLevel(logging.INFO) |
| 19 | + # create the logging file handler |
| 20 | + fh = logging.FileHandler("/path/to/test.log") |
| 21 | + fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
| 22 | + formatter = logging.Formatter(fmt) |
| 23 | + fh.setFormatter(formatter) |
| 24 | + # add handler to logger object |
| 25 | + logger.addHandler(fh) |
| 26 | + return logger |
| 27 | + |
| 28 | + def exception(function): |
| 29 | + """ |
| 30 | + A decorator that wraps the passed in function and logs |
| 31 | + exceptions should one occur |
| 32 | + """ |
| 33 | + def wrapper(*args, **kwargs): |
| 34 | + logger = create_logger() |
| 35 | + try: |
| 36 | + return function(*args, **kwargs) |
| 37 | + except: |
| 38 | + # log the exception |
| 39 | + err = "There was an exception in " |
| 40 | + err += function.__name__ |
| 41 | + logger.exception(err) |
| 42 | + # re-raise the exception |
| 43 | + raise |
| 44 | + return wrapper |
| 45 | +#+END_SRC |
| 46 | + |
| 47 | +在这段代码中,定义了两个函数. 地一个函数创建并返回了一个logging对象. 第二个函数为我们的装饰器函数,其中我们将传入的函数包裹进一个try/except中,并使用logger记录下任何产生的异常. 同时你还会发现,我还记录下了产生异常的函数名. |
| 48 | + |
| 49 | +现在让我们测试一下这个装饰器. 创建一个新Python脚本并添加以下代码. 请确保这个新Python脚本与上面创建装饰器的脚本在同一个目录下. |
| 50 | +#+BEGIN_SRC python |
| 51 | + from exception_decor import exception |
| 52 | + |
| 53 | + @exception |
| 54 | + def zero_divide(): |
| 55 | + 1 / 0 |
| 56 | + |
| 57 | + if __name__ == '__main__': |
| 58 | + zero_divide() |
| 59 | +#+END_SRC |
| 60 | + |
| 61 | +当你在命令行中运行该代码后,你会发现多除了一个日志文件,其内容为: |
| 62 | +#+BEGIN_EXAMPLE |
| 63 | + 2016-06-09 08:26:50,874 - example_logger - ERROR - There was an exception in zero_divide |
| 64 | + Traceback (most recent call last): |
| 65 | + File "/home/mike/exception_decor.py", line 29, in wrapper |
| 66 | + return function(*args, **kwargs) |
| 67 | + File "/home/mike/test_exceptions.py", line 5, in zero_divide |
| 68 | + 1 / 0 |
| 69 | + ZeroDivisionError: integer division or modulo by zero |
| 70 | +#+END_EXAMPLE |
| 71 | + |
| 72 | +我觉得这份代码很方便,我希望你们大家也会觉得有用. |
0 commit comments