如何将`logging`警告变成错误?

xeb*_*btl 1 python logging

我使用的库通过logging模块(logging.Logger'swarn()error()方法)发出警告和错误。我想实现一个将警告转换为错误的选项(即,警告失败)。

有没有简单的方法来实现这一目标?

通过查看文档,我看不到现成的解决方案。我认为通过添加自定义Handler对象是可能的,但我不确定如何“正确”做到这一点。任何指针?

Vin*_*jip 5

@hoefling's answer is close, but I would change it like so:

class LevelRaiser(logging.Filter):
    def filter(self, record):
        if record.levelno == logging.WARNING:
            record.levelno = logging.ERROR
            record.levelname = logging.getLevelName(logging.ERROR)
        return True

def configure_library_logging():
    library_root_logger = logging.getLogger(library.__name__)
    library_root_logger.addFilter(LevelRaiser())
Run Code Online (Sandbox Code Playgroud)

The reason is that filters are used to change LogRecord attributes and filter stuff out, whereas handlers are used to do I/O. What you're trying to do here isn't I/O, and so doesn't really belong in a handler.