为什么日志消息在父进程中重复?

时间:2014-05-14 08:39:11

标签: python logging

我创建了这样的新流程:

from multiprocessing import Process
import logging.handlers
import time

def new_log(file_name, level):
    log = logging.getLogger()
    h = logging.handlers.RotatingFileHandler(file_name, maxBytes=10485760)
    h.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s: %(message)s'))
    log.addHandler(h)

    log_level = logging.DEBUG
    if level == 'debug':
        log_level = logging.DEBUG
    elif level == 'info':
        log_level = logging.INFO
    elif level == 'warn':
        log_level = logging.WARN
    elif level == 'error':
        log_level = logging.ERROR
    elif level == 'critical':
        log_level = logging.CRITICAL

    log.setLevel(log_level)
    return log

def func():
    child_logger = new_log('child', 'debug')
    for i in range(0, 10):
        child_logger.debug('child process running on %d' % i)
        time.sleep(1)

def father():
    father_logger = new_log('father', 'debug')
    father_logger.debug('this is father process')
    proc = Process(target = func, args = ())
    proc.start()

father()

两个不同的记录器会记录不同的消息,但是当child_logger记录一些消息时,father_logger仍会记录相同的消息,为什么会发生这种情况?如何禁用此行为?

1 个答案:

答案 0 :(得分:0)

getLogger()返回根记录器。这意味着每次调用new_logger()时,它都会向根记录器添加一个新的处理程序并设置根记录器级别。

使用此功能为每次通话获取一个新的记录器并设置它的级别:

log = logging.getLogger(file_name)
h = logging.handlers.RotatingFileHandler(file_name, maxBytes=10485760)
h.setLevel(level)

注意:当记录器接受它们时,使用大写字符串作为级别,即“调试”和“#39; DEBUG'将它工作而不将其转换为logging.DEBUG