Python教程

python 装饰器 log

本文主要是介绍python 装饰器 log,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

定义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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!