定义logger方法:
import logging
import os
import time
import utils
data=time.strftime("%Y-%m-%d-%H:%M:%s")
logging.basicConfig(filename=utils.get_project_path()+"log/"+data,filemode='a',format='[%(asctime)s-%(filename)s:%(message)s]')
def logger(level):
def wrapper(func):
def inner_wrapper(*args,**kwargs):
msg="[{level}]:enter function {func} ()".format(level=level,func=func.__name__)
print(msg)
logging.log(msg=msg,level=30)
#logging.log(level=10,msg=msg)
return func(*args,**kwargs)
return inner_wrapper
return wrapper
def logger1(func):
def wapper(*args,**kwargs):
msg="[DEBUG]:enter function {func} ()".format(func=func.__name__)
logging.log(level=40,msg=msg)
return func(*args,**kwargs)
return wapper
使用:
@logger("deBUG")
@logger1
def run_cmd(self,command):
ret=subprocess.Popen(command,shell=True,stdout=subprocess.PIPE).stdout.read()
ret=ret.decode('gbk')
if ret.strip()=="":
print("error:{}".format(str(ret)))
else:
print("Success:{}".format(str(ret)))
return ret
运行结果:
[2021-05-31 18:55:08,862-logger.py:[deBUG]:enter function wapper ()]
[2021-05-31 18:55:08,862-logger.py:[DEBUG]:enter function run_cmd ()]
总结
以上是内存溢出为你收集整理的python 装饰器 log全部内容,希望文章能够帮你解决python 装饰器 log所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)