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
参考: