[Python] Pytest caplog not capturing logs

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    See my minimal example below for reproducing the issue:

    import logging
    import logging.config


    def test_logging(caplog):
    LOGGING_CONFIG = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
    "default": {
    "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    },
    },
    "handlers": {
    "console": {
    "class": "logging.StreamHandler",
    "formatter": "default",
    "level": "DEBUG",
    },
    },
    "loggers": {
    "": { # root logger
    "handlers": ["console"],
    "level": "DEBUG",
    "propagate": True,
    },
    },
    }

    logging.config.dictConfig(LOGGING_CONFIG)

    logger = logging.getLogger("root_module.sub1.sub2")
    logger.setLevel(logging.DEBUG)

    assert logger.propagate is True
    assert logger.getEffectiveLevel() == logging.DEBUG

    with caplog.at_level(logging.DEBUG):
    logger.debug(" DEBUG msg")
    logger.info(" INFO msg")
    logger.warning("⚠️ WARNING msg")
    logger.error("❌ ERROR msg")
    logger.critical(" CRITICAL msg")

    print(" caplog.messages:", caplog.messages)

    # Final assertion
    assert any("CRITICAL" in r or "" in r for r in caplog.messages)


    Running pytest -s outputs:

    tests/test_logs.py 2025-04-16 17:06:03,983 - root_module.sub1.sub2 - DEBUG - DEBUG msg
    2025-04-16 17:06:03,983 - root_module.sub1.sub2 - INFO - INFO msg
    2025-04-16 17:06:03,983 - root_module.sub1.sub2 - WARNING - ⚠️ WARNING msg
    2025-04-16 17:06:03,983 - root_module.sub1.sub2 - ERROR - ❌ ERROR msg
    2025-04-16 17:06:03,983 - root_module.sub1.sub2 - CRITICAL - CRITICAL msg
    caplog.messages: []


    Pytest version is 8.3.5. I don't think it matters, but my setup.cfg:

    [tool:pytest]
    testpaths =
    tests


    I am expecting caplog.records to contain all 5 logs, but it is empty list.

    Continue reading...

Compartilhe esta Página