<@ULVA73B9P> Inside the on_failure hook, how can I...
# ask-marvin
y
@Marvin Inside the on_failure hook, how can I get the flow’s tags?
m
To access the flow's tags within an
on_failure
hook in Prefect, you would typically need to extract them from the
flow_run
object passed to the hook. Here's an example:
Copy code
python
from prefect import flow, get_run_logger
from prefect.blocks.core import Block

def on_failure_hook(flow, flow_run, state):
    # Access tags from the flow_run object
    tags = flow_run.tags
    logger = get_run_logger()
    <http://logger.info|logger.info>(f"Flow run failed with tags: {tags}")

@flow(on_failure=[on_failure_hook])
def my_flow():
    pass

if __name__ == "__main__":
    my_flow()
In this example, the
on_failure_hook
function accesses the
tags
attribute from the
flow_run
object. This access will give you the tags associated with the flow. You can then handle these tags as you need within the hook. For more detailed information, you can refer to the Prefect documentation on State Change Hooks.
y
@Marvin But I am getting an error about not having an active context when calling get_run_logger() inside the on_failure_hook hook.
m
When using
get_run_logger()
within an
on_failure
hook, you might encounter issues due to the lack of an active run context. A better approach is to use the
FlowRunContext
to access the logger properly. Here’s an example of how you can achieve that:
Copy code
python
from prefect import flow
from prefect.blocks.core import Block
from prefect.context import FlowRunContext

def on_failure_hook(flow, flow_run, state):
    flow_run_ctx = FlowRunContext.get()
    if flow_run_ctx:
        logger = flow_run_ctx.logger
        tags = flow_run.tags
        <http://logger.info|logger.info>(f"Flow run failed with tags: {tags}")
    else:
        print("No active FlowRunContext, cannot log the tags.")

@flow(on_failure=[on_failure_hook])
def my_flow():
    pass

if __name__ == "__main__":
    my_flow()
By utilizing
FlowRunContext.get()
, the hook can access the run context properly and leverage the logger without encountering context errors. For more details, you can refer to the Prefect documentation on Runtime Context and State Change Hooks.