Python日志文件已更新,但是虽然已设置级别,但没有任何内容打印到stdout

时间:2015-08-13 14:45:15

标签: python python-2.7 logging

我试图使用基本的python(v2.7.5)记录器:

import logging

TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S"
LOG_FORMAT = "%(asctime)s [%(levelname)s] %(message)s"
LOG_PATH = "/tmp/exaple.log"

logging.basicConfig(
    format=LOG_FORMAT,
    level=logging.DEBUG,
    filename=LOG_PATH,
    datefmt=TIMESTAMP_FORMAT
)

logger = logging.getLogger("exaple")

logger.error("example")

如您所见,'等级'设置为logging.DEBUG,该行显示在example.log按预期方式,但没有打印任何内容!为什么呢?

1 个答案:

答案 0 :(得分:1)

因为您设置了1个处理程序,所以这里有多个处理程序示例

import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('/tmp/spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

https://docs.python.org/2/howto/logging-cookbook.html#multiple-handlers-and-formatters