当前位置:首页 > 操作系统 > Windows

python日志与多处理,根记录器在Windows中不同

我尝试使用多处理进行日志记录,并在Windows下找到,我将在子进程中获得不同的根记录器,但在Linux下可以.

测试代码:

main.py:

<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import multiprocessing
from mymod import func

def m_func():
    server = multiprocessing.Process(target=func, args=())
    server.start()

logger = logging.getLogger()
#print 'in global main: ', logger

if __name__ == '__main__':
    print 'in main: ', logger
    m_func()
</code>

mymod.py:

<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging

logger = logging.getLogger()
# print 'in global func: ', logger

def func():
    print 'in func: ', logger
</code>

在Linux下,结果是:

<code>in main:  <logging.RootLogger object at 0x10e4d6d90>
in func:  <logging.RootLogger object at 0x10e4d6d90>
</code>

但是在Windows 7,64位下,我将在main和func之间获得不同的根记录器:

<code>in main:  <logging.RootLogger object at 0x00000000021FFD68>
in func:  <logging.RootLogger object at 0x00000000023BC898>
</code>

如果我在主脚本中初始化根记录器,如何在windows下保留子进程中的级别等设置?

解决方法:

在我看来,这可能与the following platform-dependant behaviour有关:

16.6.3.2. Windows
Since Windows lacks os.fork() it has a few extra restrictions:

(…)

Global variables

Bear in mind that if code run in a child process tries to access a
global variable, then the value it sees (if any) may not be the same
as the value in the parent process at the time that Process.start was
called.

However, global variables which are just module level constants cause
no problems.

从您的问题,我认为这导致logging.basicConfig()调用没有到达您的所有进程.解决此问题的方法是让您的子进程登录到队列(使用QueueHandler),并在主进程中有一个专用线程来侦听队列.


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐