Tate Wilks
10/08/2025, 5:31 PMMarvin
10/08/2025, 5:31 PMMarvin
10/08/2025, 5:32 PMfrom 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:
# 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:
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