import functools
import time
def logFunc(logger = None):
def log_decorator(function):
@functools.wraps(function)
def decorator_wrapper(*args, **kwargs):
if logger is None:
print("{2} [Debug] Enter {0}.{1}".format(function.__module__, function.__name__, time.asctime()))
result = function(*args, **kwargs)
print("{2} [Debug] Exit {0}.{1}".format(function.__module__, function.__name__, time.asctime()))
else:
logger.debug("Enter {0}.{1}".format(function.__module__, function.__name__))
result = function(*args, **kwargs)
logger.debug("Exit {0}.{1}".format(function.__module__, function.__name__))
return result
return decorator_wrapper
return log_decorator
另外,有時需要記錄函式的執行時間,一樣可以使用decorator幫助記錄。
import functools
import time
def logTime(logger = None):
def time_decorator(function):
def decorator_wrapper(*args, **kwargs):
start = time.time()
result = function(*args, **kwargs)
end = time.time()
if logger is None:
print("{3} [Debug] {0}.{1} spent {2:.3f} seconds.".format(function.__module__, function.__name__, end - start, time.asctime()))
else:
logger.debug("{0}.{1} spent {2:.3f} seconds.".format(function.__module__, function.__name__, end - start))
return result
return decorator_wrapper
return time_decorator
在這裡的logger是指logging.logger。
decorator的使用方式為:
@logFunc(logger)
def foo1():
# expressions
@logTime(logger)
def foo2():
# expressions
沒有留言:
張貼留言