首页 编程教程正文

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

piaodoo 编程教程 2020-02-02 12:36:45 980 0 python教程

这篇文章主要介绍了Python使用logging结合decorator模式实现优化日志输出的方法,实例分析了Python使用logging模块操作日志的相关技巧,需要的朋友可以参考下

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

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

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

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

运行并得到输出:

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

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

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

版权声明:

本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。

有关影视版权:本站只供百度云网盘资源,版权均属于影片公司所有,请在下载后24小时删除,切勿用于商业用途。本站所有资源信息均从互联网搜索而来,本站不对显示的内容承担责任,如您认为本站页面信息侵犯了您的权益,请附上版权证明邮件告知【754403226@qq.com】,在收到邮件后72小时内删除。本文链接:http://www.piaodoo.com/2622.html

评论

搜索