Slackbot
10/17/2025, 6:40 PMMarvin
10/17/2025, 6:40 PMMarvin
10/17/2025, 6:43 PMget_run_logger() only works while a flow or task is actually running. At import time (including during deployment build/import), there is no active run context, so get_run_logger() raises MissingContextError.
- You’re calling get_run_logger() at module import time (reader.py top-level), which triggers the error during deployment/import.
How to fix it
Pick one of these patterns:
1) Use a module-level logger that does not require a run context
- Safe for imports and deployment builds.
# reader.py
from prefect.logging import get_logger
logger = get_logger(__name__) # safe at import time
def apply_grouping(...):
<http://logger.info|logger.info>("apply_grouping called")
...
- Then, inside your tasks/flows (where a run context exists), use get_run_logger() if you want run-context logs routed to Prefect:
from prefect import task, get_run_logger
@task
def apply_grouping_task(...):
run_logger = get_run_logger()
<http://run_logger.info|run_logger.info>("running apply_grouping")
return apply_grouping(...)
2) Lazy/fallback logger (works both inside and outside a run)
- Use run logger if available; otherwise fall back to a standard Prefect logger.
# reader.py
from prefect.exceptions import MissingContextError
from prefect import get_run_logger
from prefect.logging import get_logger as get_prefect_logger
def get_logger_safe():
try:
return get_run_logger()
except MissingContextError:
return get_prefect_logger(__name__)
logger = get_logger_safe()
A note on “code not getting executed”
- Importing a module does not execute function bodies; it only runs top-level statements. If you expect certain logic to run as part of the flow, put it inside a @flow or @task and call it from the flow. Avoid relying on import-time side effects in Prefect projects—deployment builds will import your code but not run your flows/tasks.
Docs
- Prefect 2 logging guide: Logging in Prefect 2
- Runtime context (why get_run_logger needs a context): Runtime context in Prefect 2
If you can share a small snippet of how reader.apply_grouping is defined and where it’s called, I can suggest the exact refactor to ensure your code runs when you expect and logs to Prefect properly.