def get_cloud_logging_url()

in functions/orchestration-helpers/intermediate/main.py [0:0]


def get_cloud_logging_url(target_function_url):
    """
    Retrieves the Cloud Logging URL for the most recent execution of a specified Google Cloud Function.

    Args:
        target_function_url (str): The URL of the target Google Cloud Function.

    Returns:
        str: The Cloud Logging URL for the most recent execution of the function,
             or None if no matching log entries are found.
    """
    date = datetime.utcnow() - timedelta(minutes=59)
    function_name = target_function_url.split('/')[-1]

    # Remove newline characters and extra whitespace from the filter string
    filter_str = f"""
        (resource.type="cloud_function" AND resource.labels.function_name="{function_name}") 
        OR 
        (resource.type="cloud_run_revision" AND resource.labels.function_name="{function_name}") 
        AND timestamp>="{date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")}" 
    """
    filter_str = ' '.join(filter_str.split())  # Remove extra whitespace

    # Then apply the double URL encoding (TODO enhance encoding to get URL link)
    encoded_filter = parse.quote(parse.quote(filter_str, safe=''), safe='')
    encoded_filter = (
        encoded_filter
        .replace('%253D%2522', '%20%3D%20%22')
        .replace("%2522%2520", "%22%0A%20")
        .replace("%2520", "%20")
        .replace("%2522%2529%20", "%22%2529%0A%20")
        .replace("%253E%20%3D%20%", "%3E%3D%")
        .replace("%253A", ":")
        .replace("Z%2522", "Z%22")
    )
    base_url = "https://console.cloud.google.com/logs/query"
    query_params = f";query={encoded_filter}"
    log_url = f"{base_url}{query_params}"
    print("Cloud Logging URL query:", log_url)
    return log_url