练习内容:使用两种不同方式,编写一个可接受参数的logging装饰器函数
方式一:
1 __author__ = 'Orcsir' 2 from functools import wraps 3 import logging 4 5 6 def logged(level, name=None, message=None): 7 def decorate(func): 8 logname = name if name else func.__module__ 9 log = logging.getLogger(logname) 10 logmsg = message if message else func.__name__ 11 12 @wraps(func) 13 def wrapper(*args, **kwargs): 14 log.log(level, logmsg) 15 return func(*args, **kwargs) 16 17 return wrapper 18 19 return decorate 20 21 # Test 22 @logged(logging.DEBUG) 23 def add(x, y): 24 print("add func") 25 return x + y 26 27 28 @logged(logging.WARNING, message='example') 29 def spam(): 30 print("Spam") 31 32 add(1, 2) 33 spam()
方式二:使用partial函数,减少装饰器内部函数定义
1 __author__ = 'Orcsir' 2 3 from functools import wraps, partial 4 import logging 5 6 7 def logged(func=None, level=logging.INFO, name="", message=""): 8 if func is None: 9 return partial(logged, level=level, name=name, message=message) 10 11 logname = name if name else func.__module__ 12 log = logging.getLogger(logname) 13 logmsg = message if message else func.__name__ 14 15 @wraps(func) 16 def wrapper(*args, **kwargs): 17 log.log(level, logmsg) 18 return func(*args, **kwargs) 19 20 return wrapper 21 22 23 # Test 24 @logged(level=logging.WARNING) 25 def add(x, y): 26 print("add func") 27 return x + y 28 29 30 @logged(level=logging.WARNING, message='example') 31 def spam(): 32 print("Spam") 33 34 add(1, 2) 35 spam()