launchdarkly-metric-instrument
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLaunchDarkly Metric Instrument
LaunchDarkly 指标埋点
You're using a skill that will guide you through adding a 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。
track()Prerequisites
前置要求
This skill requires the remotely hosted LaunchDarkly MCP server to be configured in your environment.
Required MCP tools:
- — verify events are flowing after instrumentation
list-metric-events
Optional MCP tools (enhance workflow):
- — retrieve the SDK key for the right environment when SDK initialization is needed
get-project
本技能需要你在环境中配置好远程托管的LaunchDarkly MCP服务器。
所需MCP工具:
- — 验证埋点完成后事件是否正常上报
list-metric-events
可选MCP工具(优化工作流):
- — 需要初始化SDK时,获取对应环境的SDK密钥
get-project
Workflow
工作流
Step 1: Detect the SDK
步骤1:识别SDK
Before writing any code, understand the LaunchDarkly setup already in this codebase.
-
Search for existingcalls. This is the fastest signal:
track()- 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.
- Look for
-
Search for SDK imports and initialization if nocalls exist:
track()- Check ,
package.json,requirements.txt,go.mod,Gemfilefor an LD SDK dependency*.csproj - Look for ,
LDClient,ldclient,launchdarkly-server-sdk,launchdarkly-node-server-sdk, etc.launchdarkly-react-client-sdk - Find the initialization block to understand how the client is accessed across the codebase
- Check
-
Determine client-side or server-side. This is the most critical distinction — it determines thesignature:
track()SDK type signaturetrack()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配置。
-
**搜索现有的调用。**这是最快的判断依据:
track()- 查找、
ldClient.track(、.track(ld.track( - 如果存在相关调用,你可以直接从中获知SDK类型、调用签名和上下文使用模式,直接照搬即可。
- 查找
-
如果没有找到调用,则搜索SDK导入和初始化代码:
track()- 检查、
package.json、requirements.txt、go.mod、Gemfile中是否有LD SDK依赖*.csproj - 查找、
LDClient、ldclient、launchdarkly-server-sdk、launchdarkly-node-server-sdk等关键词launchdarkly-react-client-sdk - 找到初始化代码块,了解整个代码库中客户端的调用方式
- 检查
-
**判断是客户端还是服务端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.
-
Detect the package manager from lockfiles:/
package-lock.json/yarn.lock→ npm/yarn/pnpm;pnpm-lock.yaml/Pipfile.lock→ pip/poetry;poetry.lock→ go modules;go.sum→ bundler.Gemfile.lock -
Install the appropriate SDK using the detected package manager. See SDK Track Patterns for the right package name per language.
-
Get the SDK key using— fetch the project and choose the key for the environment the user wants to instrument (typically
get-projectorproductionfor initial testing).staging -
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则跳过此步骤。
-
通过锁文件识别包管理器:/
package-lock.json/yarn.lock→ npm/yarn/pnpm;pnpm-lock.yaml/Pipfile.lock→ pip/poetry;poetry.lock→ go modules;go.sum→ bundler。Gemfile.lock -
**使用识别到的包管理器安装对应SDK。**查看SDK Track Patterns获取各语言对应的包名。
-
使用获取SDK密钥 — 拉取项目信息,选择用户需要埋点的环境对应的密钥(初始测试通常用
get-project或production)。staging -
**按照代码库现有模式添加SDK初始化代码。**如果有统一配置或服务层,将LD客户端添加到对应位置。查看SDK Track Patterns获取初始化示例。
Step 3: Find the Right Placement
步骤3:找到正确的插入位置
Locate where in the code the user action or event occurs.
-
Ask if you're not sure where the action happens. Don't guess at placement — acall in the wrong location (e.g. a render method instead of a submit handler) produces misleading data.
track() -
Look for signals of the right location:
- Form submissions, button click handlers, API route completions, mutation hooks
- Existing analytics calls (,
segment.track(),mixpanel.track()) — these are often co-located with where LD track calls should gogtag() - Comments like
// TODO: track this
-
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? -
Proceed once confirmed (or if you're confident enough from codebase signals).
定位代码中用户操作或事件发生的位置。
-
**如果不确定操作发生的位置直接询问用户。**不要猜测插入位置 — 把调用放在错误位置(比如放在渲染方法而不是提交处理函数中)会产生错误数据。
track() -
查找正确位置的特征:
- 表单提交、按钮点击处理函数、API路由完成逻辑、mutation钩子
- 现有的分析调用(、
segment.track()、mixpanel.track())——这些位置通常和LD track调用应该放置的位置重合gtag() - 类似的注释
// TODO: track this
-
在编写代码前向用户确认候选位置:
I'll add the track() call here, in the checkout submit handler (src/checkout/CheckoutForm.tsx, line 47). Does that look right? -
确认后再继续(或者你从代码库特征中已经有足够把握的情况下也可以直接继续)。
Step 4: Write the track()
Call
track()步骤4:编写track()
调用
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 metrics — include with the numeric measurement:
valuemetricValuetypescript
// 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 calls) and use the same one. This is how LD correlates the event to the right experiment participant.
variation() - only for
metricValuemetrics. Forvalueandcountmetrics, omitoccurrenceentirely.metricValue - Respect wrapper patterns. If the codebase wraps LD calls behind a utility (,
featureFlags.track()), add the new call through that wrapper — not by callinganalytics.ldTrack()directly.ldClient - Match the event key exactly. event keys are case-sensitive. Use the exact string that the metric was created with.
track()
See SDK Track Patterns for full per-language examples.
按照步骤1中找到的模式编写调用代码。
服务端SDK — 必须传入上下文:
typescript
ldClient.track('checkout-completed', context);客户端SDK — 上下文是隐式的:
typescript
ldClient.track('checkout-completed');对于类型指标 — 传入携带数值度量:
valuemetricValuetypescript
// 服务端:延迟指标(毫秒)
ldClient.track('api-response-time', context, null, responseTimeMs);
// 客户端:收入指标
ldClient.track('purchase-completed', { orderId }, purchaseAmountUSD);核心规则:
- **匹配现有上下文。**不要内联构建新的上下文。找到代码库中已有的构建上下文/用户对象的位置(用于调用的对象),使用同一个对象。这样LD才能将事件关联到正确的实验参与者。
variation() - **仅类型指标需要
value。**对于metricValue和count类型指标,直接省略occurrence即可。metricValue - **遵循封装模式。**如果代码库将LD调用封装在工具函数后(、
featureFlags.track()),通过封装添加新调用 —— 不要直接调用analytics.ldTrack()。ldClient - 严格匹配事件key。的事件key是大小写敏感的。使用创建指标时的 exact 字符串。
track()
查看SDK Track Patterns获取各语言的完整示例。
Step 5: Verify
步骤5:验证
Guide the user to trigger the action in their local or staging environment. Then use to confirm the event key appears:
list-metric-eventslist-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:
| Problem | Check |
|---|---|
| Wrong event key casing | Does the |
| SDK not initialized | Is |
| Server-side: wrong context | Is the context passed to |
| Client-side: no flag evaluation first | Has the SDK initialized and identified the user before |
| Wrong environment | Is |
| Data delay | |
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 环境触发对应操作。然后使用确认事件key出现:
list-metric-eventslist-metric-events(projectKey, environmentKey)**如果事件key出现:**确认成功并展示总结。
如果触发后事件key没有出现,按照以下检查清单排查:
| 问题 | 检查项 |
|---|---|
| 事件key大小写错误 | |
| SDK未初始化 | |
| 服务端:上下文错误 | 传入 |
| 客户端:未先进行Flag求值 | |
| 环境错误 | |
| 数据延迟 | |
验证通过后展示总结:
✓ 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
重要说明
- calls only count in experiments when a flag is evaluated first. The event is correlated to an experiment participant because LD saw a
track()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.variation() - Client-side SDKs flush events on an interval (default ~30 seconds) or on page unload. In tests, you may need to call explicitly to see events appear immediately.
ldClient.flush() - Server-side SDKs also buffer events. Calling after
ldClient.flush()in development ensures the event is sent before the process exits or the test ends.track() - units must match the metric definition. If the metric was created with unit
metricValue, pass milliseconds. Passing seconds into a milliseconds metric will produce silently wrong results.ms - The parameter is for custom metadata, not the metric value. Pass extra context (order ID, category, etc.) in
data. Pass the numeric measurement indata.metricValue
- **只有先对Flag求值后,调用才会被计入实验统计。**LD会将事件关联到实验参与者,因为它检测到了来自该上下文的
track()调用。如果用户触发操作时没有对任何Flag求值,事件可能仍会被采集,但不会出现在实验结果中。variation() - 客户端SDK会按间隔上报事件(默认约30秒)或在页面卸载时上报。在测试中,你可能需要显式调用让事件立即上报。
ldClient.flush() - **服务端SDK也会缓存事件。**开发环境中在后调用
track()可以确保事件在进程退出或测试结束前发送。ldClient.flush() - **的单位必须和指标定义匹配。**如果指标创建时设置的单位是
metricValue,就传入毫秒值。给毫秒单位的指标传入秒值会产生无提示的错误结果。ms - **参数用于存储自定义元数据,不是指标值。**在
data中传入额外上下文(订单ID、分类等),在data中传入数值度量。metricValue
References
参考资料
- SDK Track Patterns — call syntax, initialization, and package names for every supported SDK
track()
- SDK Track Patterns — 所有支持的SDK的调用语法、初始化方法和包名
track()