在函数中嵌入装饰器

我们回到日志的例子,并创建一个包裹函数,能让我们指定一个用于输出的日志文件。

  1. from functools import wraps
  2. def logit(logfile='out.log'):
  3. def logging_decorator(func):
  4. @wraps(func)
  5. def wrapped_function(*args, **kwargs):
  6. log_string = func.__name__ + " was called"
  7. print(log_string)
  8. # 打开logfile,并写入内容
  9. with open(logfile, 'a') as opened_file:
  10. # 现在将日志打到指定的logfile
  11. opened_file.write(log_string + '\n')
  12. return func(*args, **kwargs)
  13. return wrapped_function
  14. return logging_decorator
  15. @logit()
  16. def myfunc1():
  17. pass
  18. myfunc1()
  19. # Output: myfunc1 was called
  20. # 现在一个叫做 out.log 的文件出现了,里面的内容就是上面的字符串
  21. @logit(logfile='func2.log')
  22. def myfunc2():
  23. pass
  24. myfunc2()
  25. # Output: myfunc2 was called
  26. # 现在一个叫做 func2.log 的文件出现了,里面的内容就是上面的字符串