gpt4 book ai didi

Python 2.7 多处理日志记录和循环

转载 作者:行者123 更新时间:2023-12-01 05:16:56 26 4
gpt4 key购买 nike

如何将我的两个进程登录到一个唯一的文件中?使用我的代码,只有 proc1 正在记录到我的日志文件中......模块.py:

import multiprocessing,logging

log = multiprocessing.log_to_stderr()
log.setLevel(logging.DEBUG)
handler = logging.FileHandler('/var/log/my.log')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)

def proc1():
log.info('Hi from proc1')
while True:
if something:
log.info('something')

def proc2():
log.info('Hi from proc2')
while True:
if something_more:
log.info('something more')

if __name__ == '__main__':
p1 = multiprocessing.Process(target=proc1)
p2 = multiprocessing.Process(target=proc2)
p1.start()
p2.start()

最佳答案

正如 https://docs.python.org/2/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes 所说

"Although logging is thread-safe, and logging to a single file from multiple threads in a single process is supported, logging to a single file from multiple processes is not supported"

然后,您应该找到另一种方法来获取它,即实现日志服务器:

https://docs.python.org/2/howto/logging-cookbook.html#sending-and-receiving-logging-events-across-a-network

关于Python 2.7 多处理日志记录和循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22996034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com