在 Python 中使用多处理时应该如何记录?

2023-12-26

现在我在框架中有一个中心模块,它使用 Python 2.6 生成多个进程multiprocessing module http://docs.python.org/library/multiprocessing.html?#module-multiprocessing。因为它使用multiprocessing,有模块级多处理感知日志,LOG = multiprocessing.get_logger(). Per the docs http://docs.python.org/library/multiprocessing.html#logging,这个记录器(EDIT) does not有进程共享锁,这样你就不会乱码sys.stderr(或任何文件句柄)通过让多个进程同时写入它。

我现在遇到的问题是框架中的其他模块不支持多处理。在我看来,我需要使这个中央模块的所有依赖项都使用多处理感知日志记录。真烦人within框架,更不用说框架的所有客户端了。还有我没有想到的替代方案吗?


我刚刚编写了自己的日志处理程序,它只是通过管道将所有内容提供给父进程。我只测试了十分钟,但似乎效果很好。

(Note:这是硬编码的RotatingFileHandler,这是我自己的用例。)


更新:@javier 现在将这种方法作为 Pypi 上可用的包进行维护 - 请参阅多处理记录 https://pypi.python.org/pypi/multiprocessing-logging/在 Pypi 上,github 上https://github.com/jruere/multiprocessing-logging https://github.com/jruere/multiprocessing-logging


更新:实施!

现在,它使用队列来正确处理并发,并且还可以正确地从错误中恢复。我现在已经在生产中使用它几个月了,下面的当前版本可以正常工作。

from logging.handlers import RotatingFileHandler
import multiprocessing, threading, logging, sys, traceback

class MultiProcessingLog(logging.Handler):
    def __init__(self, name, mode, maxsize, rotate):
        logging.Handler.__init__(self)

        self._handler = RotatingFileHandler(name, mode, maxsize, rotate)
        self.queue = multiprocessing.Queue(-1)

        t = threading.Thread(target=self.receive)
        t.daemon = True
        t.start()

    def setFormatter(self, fmt):
        logging.Handler.setFormatter(self, fmt)
        self._handler.setFormatter(fmt)

    def receive(self):
        while True:
            try:
                record = self.queue.get()
                self._handler.emit(record)
            except (KeyboardInterrupt, SystemExit):
                raise
            except EOFError:
                break
            except:
                traceback.print_exc(file=sys.stderr)

    def send(self, s):
        self.queue.put_nowait(s)

    def _format_record(self, record):
        # ensure that exc_info and args
        # have been stringified.  Removes any chance of
        # unpickleable things inside and possibly reduces
        # message size sent over the pipe
        if record.args:
            record.msg = record.msg % record.args
            record.args = None
        if record.exc_info:
            dummy = self.format(record)
            record.exc_info = None

        return record

    def emit(self, record):
        try:
            s = self._format_record(record)
            self.send(s)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

    def close(self):
        self._handler.close()
        logging.Handler.close(self)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Python 中使用多处理时应该如何记录? 的相关文章

随机推荐