python: 修改模块的日志级别

python: modify level of logs from a module

TLDR

如果模块使用

log.error("something happened")

我们希望看到这些日志,但作为警告,这样对我们的净影响就好像该模块使用了一样

log.warning("something happened")

更多详情

当与 confluent.cloud 的连接出现问题时,我们使用 aiokafka module which logs errors。然而,这些都是暂时性的问题,一段时间后连接会重新建立,所以我们希望这些日志是 warning 而不是 error,但是我们不想丢失那些日志。

有没有办法“即时”修改这些日志记录,以更改它们的日志级别?我知道我可以

logger = logging.getLogger("aiokafka")
logger.setLevel(logging.CRITICAL)

但是所有日志都会丢失。

您可以将过滤器功能附加到降低级别的记录器。这是一个可用于构建的工作示例:

import logging

def downgrade_filter(record):
    if record.levelno == logging.ERROR:
        record.levelno = logging.WARNING
        record.levelname = logging.getLevelName(logging.WARNING)
    return True

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s|%(name)-8s|%(message)s')
    logger = logging.getLogger('aiokafka')
    logger.setLevel(logging.WARNING)
    logger.addFilter(downgrade_filter)
    logger.debug('This should not appear')
    logger.info('This should not appear')
    logger.warning('This should appear as a warning')
    logger.error('This should appear as a warning, though logged as an error')
    logger.critical('This should appear as a critical error')

当运行时,应该打印

WARNING |aiokafka|This should appear as a warning
WARNING |aiokafka|This should appear as a warning, though logged as an error
CRITICAL|aiokafka|This should appear as a critical error

(这是 Python 3.x 的最新版本)