装饰器记录日志

from functools import wraps
import inspect
import logging


# 创建logger
logger = logging.getLogger('func_log')
logger.setLevel(logging.DEBUG)

# 写入日志
fh = logging.FileHandler('test.log')
fh.setLevel(logging.DEBUG)

# 输出控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# handler输出格式
formatter = logging.Formatter('[%(asctime)s][%(thread)d][%(filename)s][line: %(lineno)d][%(levelname)s] ## %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# 绑定handler
logger.addHandler(fh)
logger.addHandler(ch)


# 装饰器:打印函数名并写入日志
def decorator(function):
    @wraps(function)
    def inner(*args, **kwargs):
        result = function()
        logger.debug('%s is excuted!'%function.__name__)
        return result
    return inner

@decorator
def func1():
    print('%s is excuted'% inspect.stack()[0][3])  #函数内部打印方式  调用inspect模块(可注释)
    

@decorator
def func2():
    pass

if __name__ == '__main__':
    func1()
    func2()
posted @ 2019-08-31 14:32  不会玩python  阅读(7)  评论(0编辑  收藏  举报