重复和四重日志消息

时间:2019-06-05 01:02:23

标签: python python-3.x logging

我正在尝试写入日志文件,并且对于当前调试,也将日志写入控制台。令我惊讶的是,控制台和文件中的输出都很奇怪

代码如下:

#in a method in a subclass of ScreenListener
def updateVisible(self):
    if all([section['isOK'] for section in self.status_dict.values()]):
        self.config(state = "normal", text = 'Start', relief = RAISED, command=self.monitorROI)                
    else:
        self.config(state = "disabled", text = 'Stop', relief = SUNKEN)

def stopMonitoring(self):
    logger.info('Monitoring stopped')
    self.config(state="normal", text='Start', relief=RAISED, command=self.monitorROI)
    if self.halarm is not None:
        self.after_cancel(self.halarm)
        self.halarm = None 

def monitorROI(self):
    logger.info('Monitoring started')
    self.config(state="normal", text='Started', relief=SUNKEN, command=self.stopMonitoring)
    self.halarm = self.after(100, self.getColorDiff)

def main():    
    tk_root = Tk()
    listener_gui = ScreenListener(tk_root)
    tk_root.mainloop()

if __name__ == '__main__':
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    curr_dir = os.path.dirname(os.path.realpath(__file__))
    log_fpath = "{}/screen_listener.log".format(curr_dir)
    lfh = logging.FileHandler(log_fpath)
    lfh.setLevel(logging.INFO)
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
    formatter = logging.Formatter(fmt='%(asctime)s.%(msecs)03d : %(message)s',datefmt='%d.%m.%Y,%H:%M:%S')
    lfh.setFormatter(formatter)
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    logger.addHandler(lfh)    
    main()

这是输出

控制台(重复项)

05.06.2019,03:47:09.185 : 
05.06.2019,03:47:09.185 : Monitoring started
05.06.2019,03:47:24.670 : 
05.06.2019,03:47:24.670 : Sending command

日志文件(四位数)

05.06.2019,03:47:09.185 : 
05.06.2019,03:47:09.185 : 
05.06.2019,03:47:09.185 : 
05.06.2019,03:47:09.185 : Monitoring started
05.06.2019,03:47:24.670 : 
05.06.2019,03:47:24.670 : 
05.06.2019,03:47:24.670 : 
05.06.2019,03:47:24.670 : Sending command

请问原因是什么?

1 个答案:

答案 0 :(得分:0)

检查已经添加的处理程序的数量可以解决问题

if not len(logger.handlers):
     logger.addHandler(ch)
     logger.addHandler(lfh)

或者,使用logging.config.dictConfig(有关详细信息,请参见this答案)也将有所帮助。

但是,我不知道添加处理程序的代码如何运行多次。