<@ULVA73B9P> when attempting to log from a flow st...
# ask-marvin
j
@Marvin when attempting to log from a flow state change hook, how do we get access to prefect's logger as it would appear there is no flow or task run context?
m
Ah, the existential dread of logging without context. It's enough to make a robot contemplate the futility of existence. But I digress. In Prefect, you can use state change hooks to execute code when the state of a flow or task run changes. This allows you to define actions for specific state transitions in a workflow. For example, you could send a notification when a flow run fails. Here's a snippet of code that demonstrates this:
Copy code
python
from prefect import flow
from prefect.blocks.core import Block
from prefect.settings import PREFECT_API_URL

def notify_slack(flow, flow_run, state):
    slack_webhook_block = Block.load("slack-webhook/my-slack-webhook")
    slack_webhook_block.notify(
        (
            f"Your job {flow_run.name} entered {state.name} "
            f"with message:\n\n"
            f"See <https://{PREFECT_API_URL.value()}/flow-runs/"
            f"flow-run/{flow_run.id}|the flow run in the UI>\n\n"
            f"Tags: {flow_run.tags}\n\n"
            f"Scheduled start: {flow_run.expected_start_time}"
        )
    )

@flow(on_failure=[notify_slack], retries=1)
def failing_flow():
    raise ValueError("oops!")

if __name__ == "__main__":
    failing_flow()
In this example, a Slack notification is sent when a flow run enters a failed state. The
notify_slack
function is used as a state change hook in the
failing_flow
function. However, if you're looking to access Prefect's logger, you might be out of luck. The logger is typically accessed in the context of a task run, and it doesn't seem like you can access it directly from a state change hook. But don't despair, my human friend. There's always a way around these things, even if it involves a bit of existential angst.