You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过gRPC向Otel Collector发送OpenTelemetry追踪负载?

通过gRPC向OpenTelemetry Collector发送追踪负载的方法

Otel Collector默认的gRPC接收端点为localhost:4317,对应的服务方法是OpenTelemetry官方定义的opentelemetry.proto.collector.trace.v1.TraceService/Export,以下是两种常用实现方式:

方法1:使用grpcurl命令行工具(类Postman的gRPC替代方案)

grpcurl是轻量的gRPC客户端工具,支持将JSON格式的请求转为Protobuf二进制发送:

  1. 确保Otel Collector已启用gRPC接收(默认配置已开启,对应receivers.otlp.protocols.grpc端口4317)
  2. 执行命令并输入请求体:
grpcurl -plaintext -d @ localhost:4317 opentelemetry.proto.collector.trace.v1.TraceService/Export
  1. 粘贴符合OTLP规范的JSON请求(示例结构):
{
  "resourceSpans": [
    {
      "resource": {
        "attributes": [{"key": "service.name", "value": {"stringValue": "test-service"}}]
      },
      "scopeSpans": [
        {
          "scope": {"name": "test-library"},
          "spans": [
            {
              "traceId": "7bba9f334d073016e529548d6e0d7121",
              "spanId": "6e0d71217bba9f33",
              "name": "test-span",
              "kind": 1,
              "startTimeUnixNano": "1620000000000000000",
              "endTimeUnixNano": "1620000001000000000",
              "attributes": [{"key": "operation", "value": {"stringValue": "test-operation"}}]
            }
          ]
        }
      ]
    }
  ]
}

方法2:代码集成(以Python为例)

使用OpenTelemetry SDK的OTLP gRPC Exporter直接在代码中发送追踪数据:

  1. 安装依赖:
pip install opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp-proto-grpc
  1. 示例代码:
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter

# 初始化追踪器
trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)

# 配置gRPC exporter,指向Collector的gRPC端口
otlp_exporter = OTLPSpanExporter(endpoint="localhost:4317", insecure=True)
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(otlp_exporter))

# 创建并发送追踪Span
with tracer.start_as_current_span("test-grpc-span") as span:
    span.set_attribute("service.name", "test-service")
    span.set_attribute("operation", "test-operation")

# 强制刷新导出(批量处理器默认会定时导出)
trace.get_tracer_provider().force_flush()

关键注意事项

  • 若Collector配置了TLS,需在客户端添加证书参数:grpcurl用-cacert指定证书文件,代码中设置certificate_file参数
  • 确认Collector配置文件中otlp接收器的gRPC协议已开启,示例配置片段:
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317

内容的提问来源于stack exchange,提问作者shadow0wolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 00:38:32