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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

tensorflow创建变量以及根据名称查找变量

环境:Ubuntu14.04,tensorflow=1.4(bazel源码安装),Anaconda python=3.6 声明变量主要有两种方法:tf.Variable和 tf.get_...

Django生成PDF文档显示在网页上以及解决PDF中文显示乱码的问题

Django生成PDF文档显示在网页上以及解决PDF中文显示乱码的问题

项目地址:https://github.com/PythonerKK/django-generate-pdf/tree/master 这个demo实现了通过用户输入自己的个人信息生成一份...

用Pycharm实现鼠标滚轮控制字体大小的方法

用Pycharm实现鼠标滚轮控制字体大小的方法

一、pycharm字体放大的设置 File —> setting —> Keymap —>在搜寻框中输入:increase —> Increase Font Si...

tensorflow 固定部分参数训练,只训练部分参数的实例

在使用tensorflow来训练一个模型的时候,有时候需要依靠验证集来判断模型是否已经过拟合,是否需要停止训练。 1.首先想到的是用tf.placeholder()载入不同的数据来进行计...

python实现京东秒杀功能

本文实例为大家分享了python实现京东秒杀的具体代码,供大家参考,具体内容如下 # _*_coding:utf-8_*_ from selenium import webdriv...