前端之家收集整理的这篇文章主要介绍了
python 装饰器打log的简单示例,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!
# @param 用python 装饰器打log
# @author 编程之家 jb51.cc|jb51.cc
#! /usr/bin/env python
# coding=utf-8
from time import time
def logged(when):
def log(f,*args,**kargs):
print("called: function:%s,args:%r,kargs:%r"%(f,args,kargs))
def pre_logged(f):
def wrapper(*args,**kargs):
log(f,**kargs)
return f(*args,**kargs)
def post_logged(f):
def wrapped(*args,**kargs):
now=time()
try:
return f(*args,**kargs)
finally:
log(f,**kargs)
print("time delta:%s"%(time()-now))
return wrapped
try:
#从这里开始调用
return{"pre":pre_logged,"post":post_logged}[when]
except Exception as e:
print(e)
@logged("post")
def hello(name):
print("hello",name)
@logged("post")
def test(a,b=1):
print(a+b)
hello("world")
test(1,2)
# End www.jb51.cc