Skip to main content
 首页 » 编程设计

Python 日志文件已更新,但尽管设置了级别,但没有任何内容打印到标准输出

2025年05月04日15傻小

我正在尝试使用基本的 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") 

如您所见,'level' 设置为 logging.DEBUG,该行按预期出现在 example.log 中,但未打印任何内容!为什么?

请您参考如下方法:

因为您设置了 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