码迷,mamicode.com
首页 > 编程语言 > 详细

python 装饰器 log

时间:2021-06-02 19:50:48      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:else   open   %s   format   print   logging   roc   elf   **kwargs   

定义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

标签:else   open   %s   format   print   logging   roc   elf   **kwargs   

原文地址:https://www.cnblogs.com/judith0719/p/14836423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!