Python MultiProcess, Logging, Various Classes

六月ゝ 毕业季﹏ 提交于 2019-12-02 08:43:01

Here's some sample code that works with zzzeek's handler:

mtlog = MultiProcessingLog('foo.log', 'a', 0, 0)
logging.getLogger().addHandler(mtlog)

def task(_):
    logging.error('Hi from {}'.format(os.getpid()))

p = multiprocessing.Pool()
p.map(task, range(4))

Here's my running it:

$ python mtlog.py
$ cat foo.log
Hi from 6179
Hi from 6180
Hi from 6181
Hi from 6182

In fact, any trivial test I come up with works just fine. So clearly, you're doing something wrong, probably the same thing, in all of your attempts.


My first guess is that you're trying to use it on Windows. As Noah Yetter's comment says:

Unfortunately this approach doesn't work on Windows. From docs.python.org/library/multiprocessing.html 16.6.2.12 "Note that on Windows child processes will only inherit the level of the parent process’s logger – any other customization of the logger will not be inherited." Subprocesses won't inherit the handler, and you can't pass it explicitly because it's not pickleable.

Although zzzeek replies that he thinks it'll work, I'm 90% sure he's wrong:

I think that only refers to the logger that's hardwired into the multiprocessing module. This recipe isn't making any usage of that nor should it care about propagation of loglevels, it just shuttles data from child to parent using normal multiprocessing channels.

That's exactly backward. Propagation of log levels does work; propagation of addHandler does not.

To make this work, you'd need to pass the queue explicitly to the children, and build the child-side logger out of that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!