Skip to content

Commit 7c77047

Browse files
authored
fix(sdk): support custom metrics (#446)
1 parent f9ff60d commit 7c77047

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

packages/sample-app/src/sample_decorators.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ class SampleOpenAI {
3131
prompt: `Tell me a joke about ${jokeSubject}`,
3232
model: "gpt-3.5-turbo-instruct",
3333
});
34+
traceloop.reportCustomMetric("test_metric", 50.2);
3435

3536
return completion.choices[0].text;
3637
}

packages/traceloop-sdk/src/lib/node-server-sdk.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export * from "./tracing/decorators";
88
export * from "./tracing/manual";
99
export * from "./tracing/association";
1010
export * from "./tracing/score";
11+
export * from "./tracing/custom-metric";
1112
export * from "./prompts";
1213

1314
initInstrumentations();
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { context, diag, trace } from "@opentelemetry/api";
2+
3+
/**
4+
* Reports a custom metric to the current active span.
5+
*
6+
* This function allows you to add a custom metric to the current span in the trace.
7+
* If there is no active span, a warning will be logged.
8+
*
9+
* @param {string} metricName - The name of the custom metric.
10+
* @param {number} metricValue - The numeric value of the custom metric.
11+
*
12+
* @example
13+
* reportCustomMetric('processing_time', 150);
14+
*/
15+
export const reportCustomMetric = (metricName: string, metricValue: number) => {
16+
const currentContext = context.active();
17+
const currentSpan = trace.getSpan(currentContext);
18+
19+
if (currentSpan) {
20+
currentSpan.setAttribute(
21+
`traceloop.custom_metric.${metricName}`,
22+
metricValue,
23+
);
24+
} else {
25+
diag.warn(`No active span found to report custom metric: ${metricName}`);
26+
}
27+
};

0 commit comments

Comments
 (0)