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

本文介绍了一种使用Python内置logging模块结合装饰器模式的方法来记录函数执行的日志。通过简单的装饰器可以方便地记录函数开始和结束的时间,适用于调试及性能分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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_recorder2(func):
    """装饰器, 用在func方法执行前后, 增加运行信息"""
    def wrapper(*arg, **kw):
        logging.info("Begin to execute function: %s" % func.__name__)
        func(*arg, **kw)
        logging.info("Finish executing function: %s" % func.__name__)

    return wrapper


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

 

 

 

 

 

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值