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

yipeiwu_com5年前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函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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

相关文章

Python中datetime常用时间处理方法

常用时间转换及处理函数: import datetime # 获取当前时间 d1 = datetime.datetime.now() print d1 # 当前时间加上半小时 d2...

Python实现求数列和的方法示例

本文实例讲述了Python实现求数列和的方法。分享给大家供大家参考,具体如下: 问题: 输入 输入数据有多组,每组占一行,由两个整数n(n<10000)和m(m<1000)组...

解决Matplotlib图表不能在Pycharm中显示的问题

解决Matplotlib图表不能在Pycharm中显示的问题

初学者可能都会遇到一个小问题就是:在用IPython的时候,可以使用类似 %matplotlib inline 的Magic Function(魔法函数)来显示Matplotlib...

在Python中使用poplib模块收取邮件的教程

在Python中使用poplib模块收取邮件的教程

SMTP用于发送邮件,如果要收取邮件呢? 收取邮件就是编写一个MUA作为客户端,从MDA把邮件获取到用户的电脑或者手机上。收取邮件最常用的协议是POP协议,目前版本号是3,俗称POP3。...

Python中GIL的使用详解

1、GIL简介 GIL的全称为Global Interpreter Lock,全局解释器锁。 1.1 GIL设计理念与限制 python的代码执行由python虚拟机(也叫解释器主循...