为什么记录器什么都不打印?

时间:2019-10-17 11:09:17

标签: python logging


import logging
import sys

class A(object):
    def __init__(self):
        ch = logging.StreamHandler(stream=sys.stdout)
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s: %(message)s")
        ch.setFormatter(formatter)
        logger = logging.getLogger("logger_a")
        logger.setLevel(logging.DEBUG)
        logger.addHandler(ch)
        self.logger = logger   

    def Xprint(self):
        self.logger.info("this log a!!")
        Xprint()

def Xprint():
    logger = logging.getLogger("logger_b")
    print logger.info("this log b!!")

a = A()
a.Xprint()

输出:

2019-10-17 19:02:20,574 logger_a INFO: this log a!!
None

为什么logger_b不打印任何内容?

1 个答案:

答案 0 :(得分:0)

默认loglevelWARNING。如果您也想让logger_b进行记录,则需要执行类似的操作

$ cat log.py
import logging
import sys

class A(object):
    def __init__(self):
        ch = logging.StreamHandler(stream=sys.stdout)
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s: %(message)s")
        ch.setFormatter(formatter)
        logger = logging.getLogger("logger_a")
        logger.setLevel(logging.DEBUG)
        logger.addHandler(ch)
        self.logger = logger
        self.handler = ch

    def Xprint(self):
        self.logger.info("this log a!!")
        Xprint(self.handler)

def Xprint(handler):
    logger = logging.getLogger('logger_b') # no handler is configured yet
    logger.setLevel(logging.DEBUG) # set the level
    logger.addHandler(handler) # added handler
    logger.info("this log b!!")

a = A()
a.Xprint()

输出:

$ python log.py
2019-10-17 17:02:26,418 logger_a INFO: this log a!!
2019-10-17 17:02:26,418 logger_b INFO: this log b!!