定义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 ()]