日志记录不输出调试和信息日志

Logging does not output debug & info log

我写了下面的代码:

    import logging

    logging.basicConfig(filename='rb-log.log', 
                    format='%(process)d-%(asctime)s-%(levelname)s-%(message)s',
                    level=logging.DEBUG)

    logger.debug('This is a debug message')
    logger.info('This is an info message')
    logger.warning('This is a warning message')
    logger.error('This is an error message')
    logger.critical('This is a critical message')

日志文件包含:

   646-2021-10-30 22:08:39,404-WARNING-This is a warning message
   646-2021-10-30 22:08:39,406-ERROR-This is an error message
   646-2021-10-30 22:08:39,407-CRITICAL-This is a critical message

只有 WARNING、ERROR & CRITICAL 日志被写入日志文件。未写入 DEBUG & INFO 日志。我在这里做错了什么?

您没有显示您是如何设置的 logger,所以看起来它是在配置之前。配置 (logging.basicConfig(...)) 不适用于已设置的记录器;您的记录器正在使用默认级别 WARN。

您可以在 logging 上使用便捷方法,如 https://docs.python.org/3/howto/logging.html#logging-to-a-file

logging.basicConfig(filename='rb-log.log', 
                    format='%(process)d-%(asctime)s-%(levelname)s-%(message)s',
                    level=logging.DEBUG)
logging.debug('This is a debug message')
logging.info('This is an info message')

或在创建记录器之前配置日志记录:

logging.basicConfig(filename='rb-log.log', 
                    format='%(process)d-%(asctime)s-%(levelname)s-%(message)s',
                    level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug('This is a debug message')
logger.info('This is an info message')