<@ULVA73B9P> how do I capture log output with pyte...
# ask-marvin
t
@Marvin how do I capture log output with pytest when running a prefect flow that uses the prefect run logger?
m
thought for 73.9 seconds
Assuming Prefect 3.x: use Prefect’s pytest helper to wire Prefect’s run loggers into pytest’s caplog. Quick example (one test):
Copy code
from prefect import flow, get_run_logger
from prefect.testing.fixtures import add_prefect_loggers_to_caplog

@flow
def my_flow():
    logger = get_run_logger()
    <http://logger.info|logger.info>("Hello from Prefect")
    return 42

def test_logs_are_captured(caplog):
    # Hook Prefect loggers into caplog
    add_prefect_loggers_to_caplog(caplog)

    # Capture INFO level (caplog defaults to WARNING)
    with caplog.at_level("INFO"):
        result = my_flow()
        assert result == 42

    # Assert on log content
    assert "Hello from Prefect" in caplog.text
Project-wide (recommended) via conftest.py:
Copy code
# conftest.py
import pytest
from prefect.testing.fixtures import add_prefect_loggers_to_caplog

@pytest.fixture(autouse=True)
def _prefect_caplog(caplog):
    add_prefect_loggers_to_caplog(caplog)
Then in tests, just set the level and run your flow:
Copy code
def test_logs(caplog):
    with caplog.at_level("INFO"):  # or caplog.set_level("INFO", logger="prefect")
        my_flow()
    assert "Hello from Prefect" in caplog.text
Notes: -
get_run_logger()
emits through Prefect’s logging system; the
add_prefect_loggers_to_caplog
helper ensures those records propagate to pytest’s
caplog
. - If you only want Prefect logs, you can do
caplog.set_level("INFO", logger="prefect")
. - Works for both flows and tasks using
get_run_logger()
. Docs: - Add logging in flows/tasks - Logging customization - prefect.testing.fixtures (includes add_prefect_loggers_to_caplog) - Logging API