Python日志在stdout中多次显示

时间:2015-06-03 19:01:54

标签: python logging

我目前有两节课。子类和超类。我的所有超类都是将子类中的方法线程化。子类的日志出了故障,我被告知要修复它。日志现在按顺序排列,但日志以格式重新打印,没有格式。我一整天都在努力,无法弄清楚如何解决这个问题。任何和所有建设性的帮助将不胜感激。

这是在子类......

之内
# -----------
    self.component_logger = logging.getLogger(self.__class__.__name__)
    self.stream_handler = logging.StreamHandler(sys.stdout)
    self.buffered_handler = logging.handlers.MemoryHandler(500000, flushLevel='ERROR', target=self.stream_handler)
    self.component_logger.addHandler(self.stream_handler)
    self.component_logger.addHandler(self.buffered_handler)

    self.buffered_handler.setFormatter(logging.Formatter("[%(threadName)s] %(levelname)s - %(asctime)s [%(lineno)d]: %(message)s"))
 # -----------

我在超类中调用flush

for component in components:
        t = threading.Thread(target=threaded_start, name=component.component_id, args=(component, exceptions_queue))
        t.start()
        threads.append(t)
    for t in threads:
        t.join(timeout=60)
    for component in components:
        component.buffered_handler.flush()

    #Reset log formatting
    logging.getLogger().handlers[0].setFormatter(logging.Formatter("%(levelname)s - %(asctime)s [%(lineno)d]: %(message)s"))

    #Gather results and reformat logs
    logging.info("Finished threaded starts.")

目前仍在这样打印...(一般示例)

 Starting l2-ilogin   active
 Starting l2-ilogin   active
 [L2-0] DEBUG - 2015-06-03 14:58:18,129 [57]: Starting l2-ilogin   active
 Starting l2-mgmt     active
 Starting l2-mgmt     active
 [L2-0] DEBUG - 2015-06-03 14:58:18,129 [57]: Starting l2-mgmt     active

前两个是重复,第三个是格式化版本(这是输出)。

1 个答案:

答案 0 :(得分:1)

另一个镜头:尝试将setFormatter设置为stream_handler - alfasin 18小时前

谢谢,它可以用于格式化重复的输入。我最终将self.component_logger.propogate设置为False以停止输出的重复。谢谢@alfasin。现在唯一的问题是组织子流程的输出,我应该能够做到这一点。谢谢! - 伊恩45分钟前

self.component_logger = logging.getLogger(self.__class__.__name__)
    self.stream_handler = logging.StreamHandler(sys.stdout)
    self.buffered_handler = logging.handlers.MemoryHandler(500000, flushLevel='ERROR', target=self.stream_handler)
    self.stream_handler.setFormatter((logging.Formatter("[%(threadName)s] %(levelname)s - %(asctime)s [%(lineno)d]: %(message)s")))
    # self.component_logger.addHandler(self.stream_handler)
    self.component_logger.addHandler(self.buffered_handler)
    self.component_logger.propagate = False