首页 > 编程语言 > 详细

【Python】logging结合decorator模式实优化日志输出

时间:2014-04-01 22:55:24      阅读:596      评论:0      收藏:0      [点我收藏+]

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】logging结合decorator模式实优化日志输出,布布扣,bubuko.com

【Python】logging结合decorator模式实优化日志输出

原文:http://blog.csdn.net/moxiaomomo/article/details/22748551

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!