python中用修飾器進行異常日誌記錄

當腳本中須要進行的的相同的異常操做不少的時候,能夠用修飾器來簡化代碼。好比我須要記錄拋出的異常:python

在log_exception.py文件中,app

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文件中:code

from log_exception import log_exception

@log_exception
def reciprocal(x):
    return 1/x

if __name__ == "__main__":
    reciprocal(0)

在test.log文件中能夠看到如下錯誤信息:orm

[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
相關文章
相關標籤/搜索