Generated banner for Cloud Trace Querying
Generated logo for Cloud Trace Querying

Cloud Trace Querying

GoogleOfficialPublished by Google

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Query Cloud Trace spans, filter by latency thresholds or error status, correlate distributed traces with Cloud Logging, and diagnose latency bottlenecks across Google Cloud services. Use when investigating slow requests, analyzing trace hierarchies, or resolving latency regressions. Do NOT use for querying non-GCP telemetry or database query optimization outside Cloud Trace.
— the description by Google

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The cloud-trace-querying skill enables agents to interact directly with Google Cloud Trace to investigate performance issues. It provides structured workflows to search for traces based on latency or error status, inspect trace hierarchies, and retrieve correlated application logs from Cloud Logging. The skill is designed for diagnosing latency regressions and service bottlenecks within Google Cloud environments by executing specific diagnostic scripts and formatting the results for analysis.

What it does

  • Searches for traces using latency thresholds and error filters.
  • Fetches full trace hierarchies to visualize span relationships.
  • Retrieves application logs correlated with specific trace IDs.
  • Inspects individual span attributes and metadata.
  • Generates direct Cloud Console deep links for further manual inspection.
  • Formats trace data into ASCII timelines or JSON graphs.

When to use it

  • When investigating slow requests or latency regressions in GCP services.
  • When analyzing trace hierarchies to identify bottlenecks.
  • When correlating error logs with specific distributed trace events.
  • When troubleshooting service crashes or unexpected error statuses.

Advantages

  • Provides standardized diagnostic workflows for GCP observability.
  • Enables direct correlation between distributed traces and application logs.
  • Supports flexible filtering by latency and error status.
  • Automates the generation of deep links for rapid transition to the Cloud Console.

Usage examples

“Find all traces for /v1/booking/book that took longer than 1.5 seconds.”
The agent executes the search script with the specified filter and returns a list of matching trace IDs and their durations.
“Show me the logs related to trace ID 12345.”
The agent fetches and displays application log entries correlated with the provided trace ID to help identify the root cause of an error.
“Generate a link to view trace 12345 in the Google Cloud Console.”
The agent provides a direct URL that opens the specific trace in the Cloud Trace Explorer.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/google/cloud-trace-querying/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip cloud-trace-querying.zip -d .agents/skills

Documentation by Google

Cloud Trace Querying Skill (cloud-trace-querying)

This skill equips the agent to interact with Cloud Trace by providing standard query patterns, diagnostic workflows for latency and errors, and tools to fetch and inspect trace hierarchies.

[!IMPORTANT] AUTONOMOUS TOOL EXECUTION MANDATE: You MUST execute the tool scripts directly in bash to query telemetry. Do NOT just describe query strings or write Python scripts. Run the provided bash tools directly and report the exact results.

Attribution

MUST READ: Before executing any gcloud, REST API, or MCP command, you MUST read Usage Attribution. For commands executed directly in the terminal (never in generated scripts, Terraform, or user code), prefix gcloud with CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-trace-querying)" and append agent-skills/1.0 (skill:cloud-trace-querying) to User-Agent headers.

Prerequisites & Setup

  1. Google Cloud SDK: Verify gcloud is installed (Installation Guide).

  2. Authentication: Authenticate CLI and application default credentials:

    gcloud auth login && gcloud auth application-default login
  3. Project & Billing: Identify the target <PROJECT_ID> (from the user's prompt or via bash scripts/get_trace_project/run.sh), ensure an active billing account is attached, and configure the project if not already set:

    gcloud config set project <PROJECT_ID>
  4. API Enablement: Verify Cloud Trace and Cloud Logging APIs are enabled:

    gcloud services enable cloudtrace.googleapis.com logging.googleapis.com

Quickstart Workflows

1. Identify Google Cloud Project ID

If the user specified a Google Cloud project ID in their prompt, use it.

If they did not, ALWAYS determine the Google Cloud project ID by running:

bash scripts/get_trace_project/run.sh
2. Search Traces (Latency & Errors)

To find traces matching specific criteria, such as a root span of /v1/booking/book with a duration of at least 1.5s:

bash scripts/search_traces/run.sh --filter 'root:/v1/booking/book latency:1.5s' --projects '<PROJECT_ID>'

Note: --filter is required. To list traces without specific filtering, pass --filter '' or --filter 'root:'. Filter syntax: The Cloud Trace API uses latency:<duration> (such as latency:1.5s for duration >= 1.5s), which corresponds to "Span duration" in Trace Explorer. The script outputs JSON where each cluster's examples array contains sample trace objects with trace_id, duration_seconds, span count, and error status.

3. Fetch Entire Trace Hierarchy

To view all spans and status codes/labels within a trace:

bash scripts/fetch_entire_trace/run.sh --trace-id '<TRACE_ID>' --project '<PROJECT_ID>'
4. Fetch Correlated Application Logs

To retrieve application log entries correlated with a trace ID:

bash scripts/fetch_related_logs/run.sh --trace-id '<TRACE_ID>' --trace-projects '<PROJECT_ID>'

Application log entries are useful when inspecting stack traces, exception messages, and log events emitted during span execution. When diagnosing errors or service crashes, inspect the returned log entries for severity: "ERROR" to confirm root causes or uncover unhandled exceptions. Note: fetch_related_logs queries the default log scope (_Default), searching across configured log views in the target project. An empty response can occur if: (1) no log entries match the criteria, (2) the caller lacks IAM permissions to view the matching entries, or (3) matching entries reside in log views outside the searched log scope.

5. Fetch Specific Trace Span

To inspect attributes and metadata of a single span within a trace:

bash scripts/fetch_trace_span/run.sh --trace-id '<TRACE_ID>' --span-id '<SPAN_ID>' --project '<PROJECT_ID>'

To generate direct Cloud Console URLs for browser inspection of traces or correlated logs:

bash scripts/generate_links/run.sh --trace-id '<TRACE_ID>' --project '<PROJECT_ID>' [--span-id '<SPAN_ID>']
7. Format Output
  • Terminal / CLI: Render span trees as indented ASCII timelines using |--.

  • UI Presentation: Render as A2UI JSON graph structures when requested for UI.

8. Upstream Service Error Handling

If the Cloud Trace API or Cloud Logging API returns an upstream HTTP service error (such as 500 Internal Server Error, 503 Service Unavailable, or GoogleAPICallError), report the upstream service outage directly to the user. Do not attempt to inspect virtual environments, modify internal scripts, or debug local libraries.

Reference Documentation

Operational Workflows
Query Syntax & Tools
Semantic Conventions
Concepts & Architecture
Templates & Assets

Files

scripts/fetch_related_logs/tests/main_test.py

"""Unit tests for fetch_related_logs script bundle modules."""

import datetime
import json
import unittest
from unittest import mock

# Mock google.cloud SDKs in sys.modules prior to importing log_fetcher/observability_scopes
mock_logging = mock.MagicMock()
mock_trace = mock.MagicMock()
mock_auth = mock.MagicMock()
mock_auth_transport_urllib3 = mock.MagicMock()
mock_urllib3 = mock.MagicMock()

with mock.patch.dict(
    "sys.modules",
    {
        "google.cloud": mock_logging,
        "google.cloud.logging": mock_logging,
        "google.cloud.trace_v1": mock_trace,
        "google.auth": mock_auth,
        "google.auth.transport": mock.MagicMock(),
        "google.auth.transport.urllib3": mock_auth_transport_urllib3,
        "urllib3": mock_urllib3,
    },
):
  import log_fetcher
  import main
  import observability_scopes


class TestFetchRelatedLogs(unittest.TestCase):

  def setUp(self):
    super().setUp()
    mock_logging.reset_mock()
    mock_trace.reset_mock()
    mock_auth.reset_mock()
    mock_auth_transport_urllib3.reset_mock()
    mock_urllib3.reset_mock()

    mock_auth.default.return_value = (mock.MagicMock(), "proj-a")
    self.mock_pool = mock.MagicMock()
    mock_auth_transport_urllib3.AuthorizedHttp.return_value = self.mock_pool

  def test_to_datetime_conversion(self):
    """Verifies _to_datetime handles None, protobuf Timestamp, and datetime."""
    self.assertIsNone(log_fetcher._to_datetime(None))

    now = datetime.datetime(2026, 6, 25, 13, 0, 0, tzinfo=datetime.timezone.utc)
    self.assertEqual(log_fetcher._to_datetime(now), now)

    mock_ts = mock.MagicMock(spec=["to_datetime"])
    mock_ts.to_datetime.return_value = now
    self.assertEqual(log_fetcher._to_datetime(mock_ts), now)

  def test_resolve_query_projects_only_trace(self):
    res = observability_scopes.resolve_query_projects(["proj-a"], None)
    self.assertEqual(res, {"proj-a"})

  def test_resolve_query_projects_both(self):
    res = observability_scopes.resolve_query_projects(
        ["proj-a"], ["proj-b", "proj-a"]
    )
    self.assertEqual(res, {"proj-a", "proj-b"})

  def test_resolve_query_projects_with_observability_scopes(self):
    mock_creds = mock.MagicMock()
    mock_creds.token = "mock-token"
    mock_auth.default.return_value = (mock_creds, "proj-a")

    r1 = mock.MagicMock()
    r1.status = 200
    r1.data = json.dumps({
        "name": "projects/proj-a/locations/global/scopes/_Default",
        "logScope": "projects/proj-a/locations/global/logScopes/my-scope",
    }).encode("utf-8")

    r2 = mock.MagicMock()
    r2.status = 200
    r2.data = json.dumps({
        "name": "projects/proj-a/locations/global/logScopes/my-scope",
        "resourceNames": [
            "projects/proj-monitored-1",
            "projects/proj-monitored-2",
        ],
    }).encode("utf-8")

    self.mock_pool.request.side_effect = [r1, r2]

    res = observability_scopes.resolve_query_projects(["proj-a"], ["proj-b"])
    self.assertEqual(res, {"proj-monitored-1", "proj-monitored-2", "proj-b"})

    self.mock_pool.request.assert_has_calls([
        mock.call(
            "GET",
            "https://observability.googleapis.com/v1/projects/"
            "proj-a/locations/global/scopes/_Default",
            timeout=10.0,
        ),
        mock.call(
            "GET",
            "https://logging.googleapis.com/v2/projects/proj-a/"
            "locations/global/logScopes/my-scope",
            timeout=10.0,
        ),
    ])

  def test_resolve_query_projects_observability_scopes_error_fallback(self):
    mock_creds = mock.MagicMock()
    mock_creds.token = "mock-token"
    mock_auth.default.return_value = (mock_creds, "proj-a")
    self.mock_pool.request.side_effect = Exception("API error")

    res = observability_scopes.resolve_query_projects(["proj-a"], None)
    self.assertEqual(res, {"proj-a"})

  @mock.patch.object(log_fetcher.cloud_logging, "Client")
  def test_fetch_logs_success(self, mock_logging_client_class):
    mock_logging_client = mock_logging_client_class.return_value

    mock_entry = mock.MagicMock()
    mock_entry.payload = "Test log line"
    mock_entry.timestamp = datetime.datetime(
        2026, 6, 24, 12, 0, 0, tzinfo=datetime.timezone.utc
    )
    mock_entry.severity = "INFO"
    mock_entry.log_name = "projects/trace-proj-a/logs/test-log"
    mock_entry.span_id = "span-1"
    mock_entry.trace = "projects/trace-proj-a/traces/trace-123"

    mock_logging_client.list_entries.return_value = [mock_entry]

    result = log_fetcher.fetch_logs(
        trace_id="trace-123",
        trace_projects=["trace-proj-a"],
        span_id="span-1",
        limit=5,
        start_time="2026-06-25T13:00:00Z",
        end_time="2026-06-25T14:00:00Z",
    )

    self.assertEqual(len(result), 1)
    self.assertEqual(result[0]["payload"], "Test log line")
    self.assertEqual(result[0]["timestamp"], "2026-06-24T12:00:00+00:00")
    self.assertEqual(result[0]["trace_project"], "trace-proj-a")

    mock_logging_client.list_entries.assert_called_once_with(
        resource_names=["projects/trace-proj-a"],
        filter_=(
            'trace = "projects/trace-proj-a/traces/trace-123" AND'
            ' spanId="span-1" AND timestamp >= "2026-06-25T13:00:00Z" AND'
            ' timestamp <= "2026-06-25T14:00:00Z"'
        ),
        page_size=5,
        order_by="timestamp desc",
    )

  @mock.patch.object(log_fetcher.trace_v1, "TraceServiceClient")
  @mock.patch.object(log_fetcher.cloud_logging, "Client")
  def test_fetch_logs_time_range_inference(
      self, mock_logging_client_class, mock_trace_client_class
  ):
    mock_trace_client_instance = mock_trace_client_class.return_value
    mock_logging_client_instance = mock_logging_client_class.return_value

    mock_trace_response = mock.MagicMock()

    # Test with native datetime.datetime instances (which caused the original AttributeError)
    mock_span_1 = mock.MagicMock(spec=["start_time", "end_time"])
    mock_span_1.start_time = datetime.datetime(
        2026, 6, 25, 13, 0, 5, tzinfo=datetime.timezone.utc
    )
    mock_span_1.end_time = datetime.datetime(
        2026, 6, 25, 13, 0, 10, tzinfo=datetime.timezone.utc
    )

    mock_span_2 = mock.MagicMock(spec=["start_time", "end_time"])
    mock_span_2.start_time = datetime.datetime(
        2026, 6, 25, 13, 0, 0, tzinfo=datetime.timezone.utc
    )
    mock_span_2.end_time = datetime.datetime(
        2026, 6, 25, 13, 0, 15, tzinfo=datetime.timezone.utc
    )

    mock_trace_response.spans = [mock_span_1, mock_span_2]
    mock_trace_client_instance.get_trace.return_value = mock_trace_response

    mock_entry = mock.MagicMock()
    mock_entry.payload = "Log entry within time window"
    mock_entry.timestamp = datetime.datetime(
        2026, 6, 25, 13, 0, 8, tzinfo=datetime.timezone.utc
    )
    mock_entry.severity = "INFO"
    mock_entry.log_name = "projects/trace-proj-a/logs/test-log"
    mock_entry.span_id = "span-1"
    mock_entry.trace = "projects/trace-proj-a/traces/trace-123"
    mock_logging_client_instance.list_entries.return_value = [mock_entry]

    result = log_fetcher.fetch_logs(
        trace_id="trace-123",
        trace_projects=["trace-proj-a"],
        span_id="span-1",
        limit=5,
        start_time=None,
        end_time=None,
    )

    self.assertEqual(len(result), 1)
    mock_trace_client_instance.get_trace.assert_called_once_with(
        project_id="trace-proj-a", trace_id="trace-123"
    )
    mock_logging_client_instance.list_entries.assert_called_once_with(
        resource_names=["projects/trace-proj-a"],
        filter_=(
            'trace = "projects/trace-proj-a/traces/trace-123" AND'
            ' spanId="span-1" AND timestamp >= "2026-06-25T12:59:55Z" AND'
            ' timestamp <= "2026-06-25T13:00:20Z"'
        ),
        page_size=5,
        order_by="timestamp desc",
    )

  @mock.patch.object(log_fetcher.trace_v1, "TraceServiceClient")
  @mock.patch.object(log_fetcher.cloud_logging, "Client")
  def test_fetch_logs_time_range_inference_fallback(
      self, mock_logging_client_class, mock_trace_client_class
  ):
    mock_trace_client_instance = mock_trace_client_class.return_value
    mock_logging_client_instance = mock_logging_client_class.return_value

    mock_trace_client_instance.get_trace.side_effect = Exception(
        "Trace API error"
    )
    mock_logging_client_instance.list_entries.return_value = []

    result = log_fetcher.fetch_logs(
        trace_id="trace-123",
        trace_projects=["trace-proj-a"],
        span_id="span-1",
        limit=5,
        start_time=None,
        end_time=None,
    )

    self.assertEqual(len(result), 0)
    mock_trace_client_instance.get_trace.assert_called_once_with(
        project_id="trace-proj-a", trace_id="trace-123"
    )
    mock_logging_client_instance.list_entries.assert_called_once_with(
        resource_names=["projects/trace-proj-a"],
        filter_=(
            'trace = "projects/trace-proj-a/traces/trace-123" AND'
            ' spanId="span-1"'
        ),
        page_size=5,
        order_by="timestamp desc",
    )

  @mock.patch.object(main, "fetch_logs", return_value=[{"payload": "test log"}])
  @mock.patch("builtins.print")
  @mock.patch(
      "sys.argv", ["main.py", "--trace-id", "t1", "--trace-projects", "p1"]
  )
  def test_main_cli_stdout(self, mock_print, mock_fetch):
    main.main()
    mock_fetch.assert_called_once_with(
        trace_id="t1",
        span_id=None,
        limit=100,
        trace_projects=["p1"],
        log_projects=None,
        start_time=None,
        end_time=None,
    )
    mock_print.assert_called_once()
    printed_str = mock_print.call_args[0][0]
    payload = printed_str.split(">", 1)[1].rsplit("<", 1)[0].strip()
    self.assertEqual(json.loads(payload), [{"payload": "test log"}])

  @mock.patch.object(main, "fetch_logs", return_value=[{"payload": "test log"}])
  @mock.patch(
      "sys.argv",
      [
          "main.py",
          "--trace-id",
          "t1",
          "--trace-projects",
          "p1",
          "--output",
          "out.json",
      ],
  )
  @mock.patch("builtins.open", new_callable=mock.mock_open)
  def test_main_cli_file_write(self, mock_file_open, mock_fetch):
    main.main()
    mock_fetch.assert_called_once_with(
        trace_id="t1",
        span_id=None,
        limit=100,
        trace_projects=["p1"],
        log_projects=None,
        start_time=None,
        end_time=None,
    )
    mock_file_open.assert_called_once_with("out.json", "w")
    mock_file_open().write.assert_called_once()
    written_data = mock_file_open().write.call_args[0][0]
    payload = written_data.split(">", 1)[1].rsplit("<", 1)[0].strip()
    self.assertEqual(json.loads(payload), [{"payload": "test log"}])


if __name__ == "__main__":
  unittest.main()

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs a command-line tool, Needs Python

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Google
Publisher
Google (Official)
Source
google/skills · skills/cloud/cloud-trace-querying · commit 2194d3b
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download cloud-trace-querying.zip