如何让自定义logger的内容不出现在全局的logging里面

在python编程中,logging模块是常用的一个模块,在开发过程中我们可能会遇到这样一个问题,就是我们常用的logging是记录整个程序中需要记录的内容,而一些特殊的内容我们需要只记录到一个单独的文件而不需要记录到整个logging内容里面去,这里大概实现了一个简单的demo,

import loggingfrom logging import FileHandlerg_status_logger = Nonedef init_status_logger():    global g_status_logger    if g_status_logger:        return g_status_logger    g_status_logger = logging.getLogger("s")    formatter=logging.Formatter("%(message)s")    hdlr = FileHandler('status_log')    hdlr.setLevel(logging.DEBUG)    hdlr.setFormatter(formatter)    g_status_logger.addHandler(hdlr)    g_status_logger.propagate=False    return g_status_loggerdef main():    """    -port    -log_file_prefix    """    logging.basicConfig(            level=logging.DEBUG ,            format='[%(asctime)s %(levelname)s %(lineno)d] %(message)s',    )    logger = init_status_logger()    logging.info("abc")    logger.info("efg")if __name__=="__main__":    main()

以上程序的功能就是使用的logging.info输出的abc会出现在stderr中而logger.info打印的efg只出现在status_log文件中,其中起作用的就是

g_status_logger.propagate=False

如下是这个参数的定义:

Logger.propagate

If this evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers – neither the level nor filters of the ancestor loggers in question are considered.

If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.

The constructor sets this attribute to True.

Note If you attach a handler to a logger and one or more of its ancestors, it may emit the same record multiple times. In general, you should not need to attach a handler to more than one logger – if you just attach it to the appropriate logger which is highest in the logger hierarchy, then it will see all events logged by all descendant loggers, provided that their propagate setting is left set to True. A common scenario is to attach handlers only to the root logger, and to let propagation take care of the rest.

如何让自定义logger的内容不出现在全局的logging里面

相关文章:

你感兴趣的文章:

标签云: