当前位置:Gxlcms > Python > Python使用logging结合decorator模式实现优化日志输出的方法

Python使用logging结合decorator模式实现优化日志输出的方法

时间:2021-07-01 10:21:17 帮助过:61人阅读

本文实例讲述了Python使用logging结合decorator模式实现优化日志输出的方法。分享给大家供大家参考,具体如下:

python内置的loging模块非常简便易用, 很适合程序运行日志的输出。

而结合python的装饰器模式,则可实现简明实用的代码。测试代码如下所示:

  1. #! /usr/bin/env python2.7
  2. # -*- encoding: utf-8 -*-
  3. import logging
  4. logging.basicConfig(format='[%(asctime)s] %(message)s', level=logging.INFO)
  5. def time_recorder(func):
  6. """装饰器, 用在func方法执行前后, 增加运行信息"""
  7. def wrapper():
  8. logging.info("Begin to execute function: %s" % func.__name__)
  9. func()
  10. logging.info("Finish executing function: %s" % func.__name__)
  11. return wrapper
  12. @time_recorder
  13. def first_func():
  14. print "I'm first_function. I'm doing something..."
  15. @time_recorder
  16. def second_func():
  17. print "I'm second_function. I'm doing something..."
  18. if __name__ == "__main__":
  19. first_func()
  20. second_func()

运行并得到输出:

  1. [2014-04-01 18:02:13,724] Begin to execute function: first_func
  2. I'm first_function. I'm doing something...
  3. [2014-04-01 18:02:13,725] Finish executing function: first_func
  4. [2014-04-01 18:02:13,725] Begin to execute function: second_func
  5. I'm second_function. I'm doing something...
  6. [2014-04-01 18:02:13,725] Finish executing function: second_func

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

人气教程排行