使用log装饰器,log信息总是重复记录两次

import os
import sys
import logging
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot
import functools

ENV = os.environ
def create_logger():
    logger = logging.getLogger("qtlog.log")
    #logger = logging.getLogger(ENV['TMP']+"\\qtlog.log")
    logger.setLevel(logging.INFO)
    fh = logging.FileHandler(ENV['TMP']+"\\qtlog.log")
    fmt = "\n[%(asctime)s-%(name)s-%(levelname)s]: %(message)s"
    formatter = logging.Formatter(fmt)
    fh.setFormatter(formatter)
    logger.addHandler(fh)

    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    logger.addHandler(console)

    return logger

def log_except(func):
    functools.wraps(func)
    log = create_logger()
    def wrapper(*args):
        try:
            log.info(f"run {func} with args {args}")
            results = func(*args)
        except Exception:
            log.exception("Error")
        return results
    return wrapper


log = create_logger()

#@log_except
def tmp():
    tmp2()

@log_except
def tmp2():
    log.debug("debug info")
    log.info("info info")

class My(QWidget,object):
    def __init__(self):
        super(My, self).__init__()
        self.initUI(self)

    def initUI(self,form=None):
        form.resize(100,100)
        self.pushbt = QPushButton("click",form)
        self.pushbt.move(5,10)
        self.pushbt.clicked.connect(self.pushbtclick)

        self.pushbt2 = QPushButton("Slot By Name",form)
        self.pushbt2.move(5,30)
        self.pushbt2.setObjectName("pushbt")


        QtCore.QMetaObject.connectSlotsByName(form)

    def pushbtclick(self):
        print('yes')
        tmp()

    @pyqtSlot()
    def on_pushbt_clicked(self):
        print('yes')
        tmp()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    myform = My()
    myform.show()
    sys.exit(app.exec_())

执行后,结果总是重复两次:
run <function tmp2 at ….>
run <function tmp2 at ….>
info info
info info
有什么好办法即使有装饰器,又能单独插入log记录没有?

最佳答案
def log_except(func):
    functools.wraps(func)
    # log = create_logger()    # 把这行给注释掉就好了
    def wrapper(*args):
        try:
            log.info(f"run {func} with args {args}")
            results = func(*args)
        except Exception:
            log.exception("Error")
        return results
    return wrapper
2个月前 评论
讨论数量: 3
Jason990420

可能是你建了两个 logging.getLogger,

...
def log_except(func):
    functools.wraps(func)
    log = create_logger()   # <====== Here !
    def wrapper(*args):
        try:
            log.info(f"run {func} with args {args}")
            results = func(*args)
        except Exception:
            log.exception("Error")
        return results
    return wrapper

log = create_logger()       # <====== and Here !
...
2个月前 评论
def log_except(func):
    functools.wraps(func)
    # log = create_logger()    # 把这行给注释掉就好了
    def wrapper(*args):
        try:
            log.info(f"run {func} with args {args}")
            results = func(*args)
        except Exception:
            log.exception("Error")
        return results
    return wrapper
2个月前 评论

谢谢!以为装饰器调用的log函数一定要自己调用一个,外面单独调用又加了一个。。

2个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!