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

OpenTelemetry中traceparent生成疑有误?Cloud Trace无关联追踪

如何在OpenTelemetry中获取traceparent?

以下是我编写的抽象实现:

import { context, defaultTextMapSetter } from '@opentelemetry/api';
import { W3CTraceContextPropagator } from '@opentelemetry/core';

type SqlCommentComponents = {
  traceparent?: string;
};

const renderSqlCommentComponent = (comments: SqlCommentComponents) => {
  return (
    '/*' +
    Object.entries(comments)
      .filter(([, value]) => {
        return value !== undefined;
      })
      .map(([key, value]) => {
        return `${encodeURIComponent(key)}='${encodeURIComponent(value)}'`;
      })
      .join(',') +
    '*/'
  );
};

export const getSqlcommenterComment = (): string | null => {
  const propagator = new W3CTraceContextPropagator();

  const activeContext = {};
  const sqlCommentComponents: SqlCommentComponents = {};

  propagator.inject(context.active(), activeContext, defaultTextMapSetter);

  if (
    'traceparent' in activeContext &&
    typeof activeContext.traceparent === 'string'
  ) {
    sqlCommentComponents.traceparent = activeContext.traceparent;
  }

  return Object.entries(sqlCommentComponents).length === 0
    ? null
    : renderSqlCommentComponent(sqlCommentComponents);
};

我随后使用Slonik拦截器将Sqlcommenter注释追加到SQL末尾:

interceptors.push({
  transformQuery: (queryContext, query) => {
    return {
      ...query,
      sql: `${query.sql}\n${getSqlcommenterComment() ?? ''}`,
    };

    return query;
  },
});

生成的输出看似正确:

SELECT id
FROM ip_address
WHERE
  ip_address = $1 AND
  updated_at > now() - interval '7 day'

/*traceparent='00-b1fb1430bc3932f7ad4193417161a8c0-876e8f488bbd46d2-01'*/

但在Cloud Trace中查看追踪数据时,无法看到对应的关联追踪,我怀疑自己生成traceparent的方式存在错误。

Cloud Trace界面截图


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:08:25