launchdarkly-metric-instrument

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

LaunchDarkly Metric Instrument

LaunchDarkly 指标埋点

You're using a skill that will guide you through adding a
track()
call to a codebase so a LaunchDarkly metric can measure it. Your job is to detect the SDK in use, find the right place in code to add the call, write it correctly, and verify that events are reaching LaunchDarkly.
你正在使用的技能将指导你在代码库中添加
track()
调用,以便LaunchDarkly指标可以对其进行统计。你的任务是识别当前使用的SDK,找到代码中添加调用的正确位置,正确编写调用代码,并验证事件是否成功发送到LaunchDarkly。

Prerequisites

前置要求

This skill requires the remotely hosted LaunchDarkly MCP server to be configured in your environment.
Required MCP tools:
  • list-metric-events
    — verify events are flowing after instrumentation
Optional MCP tools (enhance workflow):
  • get-project
    — retrieve the SDK key for the right environment when SDK initialization is needed
本技能需要你在环境中配置好远程托管的LaunchDarkly MCP服务器。
所需MCP工具:
  • list-metric-events
    — 验证埋点完成后事件是否正常上报
可选MCP工具(优化工作流):
  • get-project
    — 需要初始化SDK时,获取对应环境的SDK密钥

Workflow

工作流

Step 1: Detect the SDK

步骤1:识别SDK

Before writing any code, understand the LaunchDarkly setup already in this codebase.
  1. Search for existing
    track()
    calls.
    This is the fastest signal:
    • Look for
      ldClient.track(
      ,
      .track(
      ,
      ld.track(
    • If any exist, they tell you the SDK type, call signature, and context pattern in one shot — mirror those exactly.
  2. Search for SDK imports and initialization if no
    track()
    calls exist:
    • Check
      package.json
      ,
      requirements.txt
      ,
      go.mod
      ,
      Gemfile
      ,
      *.csproj
      for an LD SDK dependency
    • Look for
      LDClient
      ,
      ldclient
      ,
      launchdarkly-server-sdk
      ,
      launchdarkly-node-server-sdk
      ,
      launchdarkly-react-client-sdk
      , etc.
    • Find the initialization block to understand how the client is accessed across the codebase
  3. Determine client-side or server-side. This is the most critical distinction — it determines the
    track()
    signature:
    SDK type
    track()
    signature
    Notes
    Server-side (Node, Python, Go, Java, Ruby, .NET)
    ldClient.track(eventKey, context, data?, metricValue?)
    Context required per call
    Client-side (React, browser JS)
    ldClient.track(eventKey, data?, metricValue?)
    Context set at init, not per call
    See SDK Track Patterns for full examples by language.
编写任何代码之前,先了解当前代码库中已有的LaunchDarkly配置。
  1. **搜索现有的
    track()
    调用。**这是最快的判断依据:
    • 查找
      ldClient.track(
      .track(
      ld.track(
    • 如果存在相关调用,你可以直接从中获知SDK类型、调用签名和上下文使用模式,直接照搬即可。
  2. 如果没有找到
    track()
    调用,则搜索SDK导入和初始化代码:
    • 检查
      package.json
      requirements.txt
      go.mod
      Gemfile
      *.csproj
      中是否有LD SDK依赖
    • 查找
      LDClient
      ldclient
      launchdarkly-server-sdk
      launchdarkly-node-server-sdk
      launchdarkly-react-client-sdk
      等关键词
    • 找到初始化代码块,了解整个代码库中客户端的调用方式
  3. **判断是客户端还是服务端SDK。**这是最关键的区别,决定了
    track()
    的签名:
    SDK类型
    track()
    签名
    说明
    服务端(Node、Python、Go、Java、Ruby、.NET)
    ldClient.track(eventKey, context, data?, metricValue?)
    每次调用都需要传入上下文
    客户端(React、浏览器JS)
    ldClient.track(eventKey, data?, metricValue?)
    上下文在初始化时设置,无需每次调用传入
    查看SDK Track Patterns获取各语言的完整示例。

Step 2: Install & Initialize (if SDK not present)

步骤2:安装与初始化(如果没有SDK)

Skip this step if the SDK is already in the codebase.
  1. Detect the package manager from lockfiles:
    package-lock.json
    /
    yarn.lock
    /
    pnpm-lock.yaml
    → npm/yarn/pnpm;
    Pipfile.lock
    /
    poetry.lock
    → pip/poetry;
    go.sum
    → go modules;
    Gemfile.lock
    → bundler.
  2. Install the appropriate SDK using the detected package manager. See SDK Track Patterns for the right package name per language.
  3. Get the SDK key using
    get-project
    — fetch the project and choose the key for the environment the user wants to instrument (typically
    production
    or
    staging
    for initial testing).
  4. Add SDK initialization following the patterns already in this codebase. If there's a central config or service layer, add the LD client there. See SDK Track Patterns for initialization examples.
如果代码库中已存在SDK则跳过此步骤。
  1. 通过锁文件识别包管理器:
    package-lock.json
    /
    yarn.lock
    /
    pnpm-lock.yaml
    → npm/yarn/pnpm;
    Pipfile.lock
    /
    poetry.lock
    → pip/poetry;
    go.sum
    → go modules;
    Gemfile.lock
    → bundler。
  2. **使用识别到的包管理器安装对应SDK。**查看SDK Track Patterns获取各语言对应的包名。
  3. 使用
    get-project
    获取SDK密钥
    — 拉取项目信息,选择用户需要埋点的环境对应的密钥(初始测试通常用
    production
    staging
    )。
  4. **按照代码库现有模式添加SDK初始化代码。**如果有统一配置或服务层,将LD客户端添加到对应位置。查看SDK Track Patterns获取初始化示例。

Step 3: Find the Right Placement

步骤3:找到正确的插入位置

Locate where in the code the user action or event occurs.
  1. Ask if you're not sure where the action happens. Don't guess at placement — a
    track()
    call in the wrong location (e.g. a render method instead of a submit handler) produces misleading data.
  2. Look for signals of the right location:
    • Form submissions, button click handlers, API route completions, mutation hooks
    • Existing analytics calls (
      segment.track()
      ,
      mixpanel.track()
      ,
      gtag()
      ) — these are often co-located with where LD track calls should go
    • Comments like
      // TODO: track this
  3. Show the candidate location to the user before writing anything:
    I'll add the track() call here, in the checkout submit handler (src/checkout/CheckoutForm.tsx, line 47).
    Does that look right?
  4. Proceed once confirmed (or if you're confident enough from codebase signals).
定位代码中用户操作或事件发生的位置。
  1. **如果不确定操作发生的位置直接询问用户。**不要猜测插入位置 — 把
    track()
    调用放在错误位置(比如放在渲染方法而不是提交处理函数中)会产生错误数据。
  2. 查找正确位置的特征:
    • 表单提交、按钮点击处理函数、API路由完成逻辑、mutation钩子
    • 现有的分析调用(
      segment.track()
      mixpanel.track()
      gtag()
      )——这些位置通常和LD track调用应该放置的位置重合
    • 类似
      // TODO: track this
      的注释
  3. 在编写代码前向用户确认候选位置:
    I'll add the track() call here, in the checkout submit handler (src/checkout/CheckoutForm.tsx, line 47).
    Does that look right?
  4. 确认后再继续(或者你从代码库特征中已经有足够把握的情况下也可以直接继续)。

Step 4: Write the
track()
Call

步骤4:编写
track()
调用

Write the call following the patterns found in Step 1.
Server-side SDKs — context is required:
typescript
ldClient.track('checkout-completed', context);
Client-side SDKs — context is implicit:
typescript
ldClient.track('checkout-completed');
For
value
metrics
— include
metricValue
with the numeric measurement:
typescript
// Server-side: latency metric (ms)
ldClient.track('api-response-time', context, null, responseTimeMs);

// Client-side: revenue metric
ldClient.track('purchase-completed', { orderId }, purchaseAmountUSD);
Key rules:
  • Match the existing context. Don't construct a new context inline. Find where the codebase already builds its context/user object (used for
    variation()
    calls) and use the same one. This is how LD correlates the event to the right experiment participant.
  • metricValue
    only for
    value
    metrics.
    For
    count
    and
    occurrence
    metrics, omit
    metricValue
    entirely.
  • Respect wrapper patterns. If the codebase wraps LD calls behind a utility (
    featureFlags.track()
    ,
    analytics.ldTrack()
    ), add the new call through that wrapper — not by calling
    ldClient
    directly.
  • Match the event key exactly.
    track()
    event keys are case-sensitive. Use the exact string that the metric was created with.
See SDK Track Patterns for full per-language examples.
按照步骤1中找到的模式编写调用代码。
服务端SDK — 必须传入上下文:
typescript
ldClient.track('checkout-completed', context);
客户端SDK — 上下文是隐式的:
typescript
ldClient.track('checkout-completed');
对于
value
类型指标
— 传入
metricValue
携带数值度量:
typescript
// 服务端:延迟指标(毫秒)
ldClient.track('api-response-time', context, null, responseTimeMs);

// 客户端:收入指标
ldClient.track('purchase-completed', { orderId }, purchaseAmountUSD);
核心规则:
  • **匹配现有上下文。**不要内联构建新的上下文。找到代码库中已有的构建上下文/用户对象的位置(用于
    variation()
    调用的对象),使用同一个对象。这样LD才能将事件关联到正确的实验参与者。
  • **仅
    value
    类型指标需要
    metricValue
    。**对于
    count
    occurrence
    类型指标,直接省略
    metricValue
    即可。
  • **遵循封装模式。**如果代码库将LD调用封装在工具函数后(
    featureFlags.track()
    analytics.ldTrack()
    ),通过封装添加新调用 —— 不要直接调用
    ldClient
  • 严格匹配事件key。
    track()
    的事件key是大小写敏感的。使用创建指标时的 exact 字符串。
查看SDK Track Patterns获取各语言的完整示例。

Step 5: Verify

步骤5:验证

Guide the user to trigger the action in their local or staging environment. Then use
list-metric-events
to confirm the event key appears:
list-metric-events(projectKey, environmentKey)
If the event key appears: confirm success and show a summary.
If the event key is absent after triggering, work through this checklist:
ProblemCheck
Wrong event key casingDoes the
track()
call match the metric's event key exactly?
SDK not initializedIs
ldClient
initialized before the
track()
call runs?
Server-side: wrong contextIs the context passed to
track()
the same context used for
variation()
calls?
Client-side: no flag evaluation firstHas the SDK initialized and identified the user before
track()
is called?
Wrong environmentIs
list-metric-events
querying the same environment where the action was triggered?
Data delay
list-metric-events
shows the last 90 days with up to ~5 min delay — try again in a moment
Surface a summary once verified:
✓ Event flowing: checkout-completed
  Seen in: production
  
Next: this event is now ready to back a metric. Use the metric-create skill to set one up,
or attach an existing metric to your experiment.
引导用户在本地或 staging 环境触发对应操作。然后使用
list-metric-events
确认事件key出现:
list-metric-events(projectKey, environmentKey)
**如果事件key出现:**确认成功并展示总结。
如果触发后事件key没有出现,按照以下检查清单排查:
问题检查项
事件key大小写错误
track()
调用中的key和指标的事件key是否完全匹配?
SDK未初始化
ldClient
是否在
track()
调用运行前完成初始化?
服务端:上下文错误传入
track()
的上下文和
variation()
调用中使用的上下文是否一致?
客户端:未先进行Flag求值
track()
调用前SDK是否已完成初始化并识别了用户?
环境错误
list-metric-events
查询的环境和触发操作的环境是否一致?
数据延迟
list-metric-events
展示过去90天的数据,最多有5分钟延迟 —— 稍等片刻再尝试
验证通过后展示总结:
✓ Event flowing: checkout-completed
  Seen in: production
  
Next: this event is now ready to back a metric. Use the metric-create skill to set one up,
or attach an existing metric to your experiment.

Important Context

重要说明

  • track()
    calls only count in experiments when a flag is evaluated first.
    The event is correlated to an experiment participant because LD saw a
    variation()
    call from that context. If the user triggers the action without evaluating any flag, the event may still be ingested but won't appear in experiment results.
  • Client-side SDKs flush events on an interval (default ~30 seconds) or on page unload. In tests, you may need to call
    ldClient.flush()
    explicitly to see events appear immediately.
  • Server-side SDKs also buffer events. Calling
    ldClient.flush()
    after
    track()
    in development ensures the event is sent before the process exits or the test ends.
  • metricValue
    units must match the metric definition.
    If the metric was created with unit
    ms
    , pass milliseconds. Passing seconds into a milliseconds metric will produce silently wrong results.
  • The
    data
    parameter is for custom metadata, not the metric value.
    Pass extra context (order ID, category, etc.) in
    data
    . Pass the numeric measurement in
    metricValue
    .
  • **只有先对Flag求值后,
    track()
    调用才会被计入实验统计。**LD会将事件关联到实验参与者,因为它检测到了来自该上下文的
    variation()
    调用。如果用户触发操作时没有对任何Flag求值,事件可能仍会被采集,但不会出现在实验结果中。
  • 客户端SDK会按间隔上报事件(默认约30秒)或在页面卸载时上报。在测试中,你可能需要显式调用
    ldClient.flush()
    让事件立即上报。
  • **服务端SDK也会缓存事件。**开发环境中在
    track()
    后调用
    ldClient.flush()
    可以确保事件在进程退出或测试结束前发送。
  • **
    metricValue
    的单位必须和指标定义匹配。**如果指标创建时设置的单位是
    ms
    ,就传入毫秒值。给毫秒单位的指标传入秒值会产生无提示的错误结果。
  • **
    data
    参数用于存储自定义元数据,不是指标值。**在
    data
    中传入额外上下文(订单ID、分类等),在
    metricValue
    中传入数值度量。

References

参考资料

  • SDK Track Patterns
    track()
    call syntax, initialization, and package names for every supported SDK
  • SDK Track Patterns — 所有支持的SDK的
    track()
    调用语法、初始化方法和包名