Python多进程中的日志记录

3
如何将日志输出到多个进程的控制台? 示例:
import multiprocessing, logging, multiprocessing_logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
multiprocessing_logging.install_mp_handler(logger)

def worker():
    while True:
        logger.info("This is logging for TEST1")

def worker2():
    while True:
        logger.info("This is logging for TEST2")

if __name__ == '__main__':
    p1 = multiprocessing.Process(target=worker)
    p1.daemon = True
    p1.start()

    p2 = multiprocessing.Process(target=worker2)
    p2.daemon = True
    p2.start()

    p1.join()
    p2.join()

但输出结果不正确:
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST2
IINFO:root:This is logging for TEST1
NFO:root:This is logging for TEST2
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST1
IINFO:root:This is logging for TEST2
NFO:root:This is logging for TEST1
IINFO:root:This is logging for TEST2
NFO:root:This is logging for TEST1

我尝试使用multiprocessing-logging库,但它并没有起到帮助作用。


multiprocessing-logging 看起来应该可以解决您的问题 - 您能否提供一个 [MCVE] 来展示在使用它时发生了什么问题? - Florian Brucker
我只需导入multiprocessing-logging,并在配置日志后添加multiprocessing_logging.install_mp_handler(),就像链接中所写的那样。 - deniska369
在这种情况下,您应该向multiprocessing-logging提交错误报告 - Florian Brucker
我不认为这是一个 bug,因为当创建新进程时,也会创建新的日志记录器对象,但是日志记录器对象必须对所有进程都是唯一的。我认为我在使用它时出了问题。 - deniska369
然后请展示使用multiprocessing-logging的代码,这样我们可以帮助您找到问题所在。 - Florian Brucker
1个回答

1

您的(更新后的)代码在这里运行良好:

INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST1
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2
INFO:root:This is logging for TEST2

如果这对你没有用,那么你应该提交一个带有multiprocessing-logging的错误报告


IINFO:root:这是TEST2的日志记录 NFO:root:这是TEST1的日志记录 - deniska369

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接