<@ULVA73B9P> is it possible to get link to task ru...
# ask-marvin
s
@Marvin is it possible to get link to task run page in prefect Server UI from inside the task? I want to send link to task run logs in notification when the task fails
m
Yes, it is possible to get a link to the task run page in the Prefect Server UI from inside a task. You can use the Prefect 3.x API to access the task run context, which includes metadata such as the task run ID. With this ID, you can construct the URL to the task run page in your Prefect Server UI. Here's a general approach to achieve this: 1. Access Task Run Context: Within your task, you can access the task run context to retrieve the task run ID using
prefect.runtime.task_run.TaskRunContext
. 2. Construct the URL: Use the task run ID to construct the URL to the Prefect Server UI. The URL format typically follows a pattern like
http://<your-prefect-server>/task-run/<task-run-id>
. 3. Send Notification: Use your preferred method to send a notification (e.g., email, Slack) with the constructed URL when the task fails. Here is a basic example:
Copy code
python
from prefect import task, get_run_logger
from prefect.runtime.task_run import TaskRunContext

@task
def my_task():
    context = TaskRunContext.get()
    task_run_id = context.task_run_id
    prefect_server_url = "http://<your-prefect-server>/task-run/"
    task_run_url = f"{prefect_server_url}{task_run_id}"
    
    try:
        # Your task logic here
        pass
    except Exception as e:
        logger = get_run_logger()
        logger.error(f"Task failed. View logs at {task_run_url}")
        # Send notification with task_run_url
        raise e
Replace
<your-prefect-server>
with your actual Prefect Server address. For more detailed information, you can refer to the Prefect documentation and the task engine source code.
n
hi @Sergey Moskvin marvin has some details wrong but is on the right track, you can fetch the id from the runtime context and make a url but this reminds me that we do this in
runtime.flow_run
but not for tasks, so I've opened this PR which will allow for the following
Copy code
from prefect import task
import prefect.runtime
import webbrowser

@task
def open_ui():
    webbrowser.open_new_tab(prefect.runtime.task_run.ui_url)

open_ui()