手机
当前位置:查字典教程网 >脚本专栏 >python >Python使用logging结合decorator模式实现优化日志输出的方法
Python使用logging结合decorator模式实现优化日志输出的方法
摘要:本文实例讲述了Python使用logging结合decorator模式实现优化日志输出的方法。分享给大家供大家参考,具体如下:python内...

本文实例讲述了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使用logging结合decorator模式实现优化日志输出的方法】相关文章:

Python中使用动态变量名的方法

Python调用C/C++动态链接库的方法详解

Python httplib,smtplib使用方法

Python中使用中文的方法

python实现定制交互式命令行的方法

python实现网页链接提取的方法分享

python中定义结构体的方法

Python下singleton模式的实现方法

python生成指定尺寸缩略图的示例

python paramiko实现ssh远程访问的方法

精品推荐
分类导航