为跟踪添加自定义 span

您可以为跟踪添加自定义 span,以便在过程或函数的处理程序中进行更精细的跟踪。

By default, when you have tracing enabled, Snowflake starts a span for you (as described in How Snowflake represents trace events) and adds all trace events to that span. (This is known internally as the “auto_instrumented” span.) Using OpenTelemetry APIs, you can create your own spans. To the new span, you can add events and attributes using either the OpenTelemetry API or Snowflake API for your language.

例如,当您想为过程中发生的计算量大的操作(比如使用代码训练 ML 模型)隔离跟踪数据时,你可能需要创建自己的 span。

您创建的自定义 span 与 OpenTelemetry 创建的 span 的默认行为相匹配。

支持的语言

You can add custom spans from code written in the following languages, including when handler code is written with Snowpark APIs.

Language/TypeJavaPythonJavaScriptScalaSnowflake Scripting
Stored procedure handler[1]
Streamlit app
UDF handler (scalar function)[1]
UDTF handler (table function)[1] [2]

创建自定义 span

要使用处理程序代码添加自定义 span,请在现有的 Snowflake 遥测环境中使用 OpenTelemetry API 为处理程序语言创建一个新 span,根据需要添加事件和属性,然后关闭此 span。

  1. 使用 OpenTelemetry API 创建一个跟踪器来管理 span 的上下文。

通过这个在现有 Snowflake 遥测环境中创建的跟踪器,您可以创建使用现有基础设施的自定义 span,在此基础设施中,跟踪数据由事件表捕获。

  1. 在新的跟踪器中,使用一个 API 创建自定义 span,以确保新的 span 就是当前 span。

    By creating the new span in the existing context managed by Snowflake, you ensure that information from the context — including the trace_id and parent_span_id values — is passed from the Snowflake default span to other spans.

  2. When your code finishes with the custom span, it must close the span before the handler completes execution to have trace data captured by the event table.

自定义 span 的这种行为与 OpenTelemetry 的默认行为相匹配。

有关使用支持的语言添加自定义 span 的信息,请参阅以下主题:

Python 示例

Code in the following example uses the OpenTelemetry Python API (https://opentelemetry-python.readthedocs.io/en/latest/api/index.html) to create the my.span span as the current span with start_as_current_span. It then adds an event with attributes to the new span using the OpenTelemetry Python API (https://opentelemetry-python.readthedocs.io/en/latest/api/index.html).

Event data won’t be captured by the event table unless the span ends before your handler completes execution. In this example, closing the span happens automatically when the with statement concludes.

CREATE OR REPLACE FUNCTION customSpansPythonExample() RETURNS STRING
LANGUAGE PYTHON
RUNTIME_VERSION = 3.12
PACKAGES = ('opentelemetry-api')
HANDLER = 'custom_spans_function'
AS $$
from snowflake import telemetry
from opentelemetry import trace

def custom_spans_function():
  tracer = trace.get_tracer("my.tracer")
  with tracer.start_as_current_span("my.span") as span:
    span.add_event("Event2 in custom span", {"key1": "value1", "key2": "value2"})

  return "success"
$$;