简体   繁体   English

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

[英]Python 2.7 Multiprocessing logging and loops

How can I put my two processes to log in a only file? 如何将我的两个进程仅登录到一个文件中? With my code only proc1 is logging to my log file... module.py: 使用我的代码,只有proc1记录到我的日志文件中... module.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()

As said at https://docs.python.org/2/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes 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 " “尽管日志记录是线程安全的,并且支持在单个进程中从多个线程向单个文件进行日志记录,但不支持从多个进程向单个文件进行日志记录

Then, you should find another approach to get it, ie implementing a logging server: 然后,您应该找到另一种方法来实现它,即实现日志服务器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM