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

如何在Node.js中通过OTLP HTTP读取OTEL Collector追踪数据

解决OTLP HTTP Exporter数据在Node.js服务器中无法解析的问题

问题原因

OTLP HTTP Exporter默认以二进制Protobuf格式发送追踪数据,而非JSON。常规的express.json()这类中间件只能解析JSON格式的请求体,无法处理二进制Protobuf,因此会出现req.body为空的情况。

解决步骤

1. 安装依赖

需要用到处理OTLP转换的工具包和Protobuf解析库:

npm install express @opentelemetry/otlp-transformer protobufjs

2. 修改Node.js服务器代码

使用express.raw()中间件捕获原始二进制请求体,再通过OTLP的Protobuf定义解码:

const express = require('express');
const { parseProtoBuf } = require('@opentelemetry/otlp-transformer');
const { TraceService } = require('@opentelemetry/otlp-transformer/build/src/generated/opentelemetry/proto/collector/trace/v1/trace_service');

const app = express();

// 仅对/v1/traces路径使用raw中间件,指定处理application/x-protobuf类型的请求
app.use('/v1/traces', express.raw({ type: 'application/x-protobuf' }));

app.post('/v1/traces', (req, res) => {
  try {
    // 方式1:直接解码为Protobuf对象
    const traceRequest = TraceService.ExportTraceServiceRequest.decode(req.body);
    console.log('原始Protobuf解析结果:', traceRequest);

    // 方式2:用otlp-transformer转换为更易用的JS对象
    const readableTraces = parseProtoBuf(req.body, 'trace');
    console.log('转换后的追踪数据:', JSON.stringify(readableTraces, null, 2));

    res.sendStatus(200);
  } catch (err) {
    console.error('解码失败:', err);
    res.sendStatus(400);
  }
});

app.listen(8080, () => {
  console.log('服务器运行在localhost:8080');
});

3. 关键说明

  • OTLP HTTP请求的Content-Type固定为application/x-protobuf,因此express.raw()必须指定该类型才能正确捕获请求体。
  • @opentelemetry/otlp-transformer内置了官方OTLP的Protobuf定义,无需手动下载.proto文件,直接使用即可完成解码和格式转换。
  • 你的Collector配置无需修改,otlphttp exporter会自动将数据发送到http://localhost:8080/v1/traces,与服务器路径匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:47:15