Yaron Levi
06/18/2024, 8:38 AMMarvin
06/18/2024, 8:38 AMon_failure
hook in Prefect, you would typically need to extract them from the flow_run
object passed to the hook.
Here's an example:
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.Yaron Levi
06/18/2024, 9:45 AMMarvin
06/18/2024, 9:45 AMget_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:
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.