🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: allow propagation of request headers through logs (#6979)
Steffen Schmitz48673e43d720
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 40439aa73e..92a3cc7d9a 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -50,6 +50,12 @@ const EnvSchema = z.object({.enum(["trace", "debug", "info", "warn", "error", "fatal"]).optional(),LANGFUSE_LOG_FORMAT: z.enum(["text", "json"]).default("text"),+ LANGFUSE_LOG_PROPAGATED_HEADERS: z+ .string()+ .optional()+ .transform((s) =>+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],+ ),ENABLE_AWS_CLOUDWATCH_METRIC_PUBLISHING: z.enum(["true", "false"]).default("false"),diff --git a/packages/shared/src/server/headerPropagation.ts b/packages/shared/src/server/headerPropagation.tsnew file mode 100644index 0000000000..49f327fd2b--- /dev/null+++ b/packages/shared/src/server/headerPropagation.ts@@ -0,0 +1,44 @@+import * as opentelemetry from "@opentelemetry/api";+import type { IncomingHttpHeaders } from "http";+import { env } from "../env";++export type LangfuseContextProps = {+ headers?: IncomingHttpHeaders;+ userId?: string;+ projectId?: string;+};++/**+ * Returns a new context containing baggage entries composed from+ * the supplied props (headers, userId, projectId). Existing baggage+ * entries are preserved.+ */+export const contextWithLangfuseProps = (+ props: LangfuseContextProps,+): opentelemetry.Context => {+ const ctx = opentelemetry.context.active();+ let baggage =+ opentelemetry.propagation.getBaggage(ctx) ??+ opentelemetry.propagation.createBaggage();++ if (props.headers) {+ (env.LANGFUSE_LOG_PROPAGATED_HEADERS as string[]).forEach((name) => {+ const value = props.headers![name];+ if (!value) return;+ const strValue = Array.isArray(value) ? JSON.stringify(value) : value;+ baggage = baggage.setEntry(`langfuse.header.${name}`, {+ value: strValue,+ });+ });+ }+ if (props.userId) {+ baggage = baggage.setEntry("langfuse.user.id", { value: props.userId });+ }+ if (props.projectId) {+ baggage = baggage.setEntry("langfuse.project.id", {+ value: props.projectId,+ });+ }++ return opentelemetry.propagation.setBaggage(ctx, baggage);+};diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 1dab9416c9..b2a44a7c4a 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -48,6 +48,7 @@ export * from "./orderByToPrisma";export * from "./filterToPrisma";export * from "./instrumentation";export * from "./logger";+export * from "./headerPropagation";export * from "./queries";export * from "./repositories";export * from "./redis/evalExecutionQueue";diff --git a/packages/shared/src/server/instrumentation/index.ts b/packages/shared/src/server/instrumentation/index.tsindex c084bc3e95..d0e6b04bec 100644--- a/packages/shared/src/server/instrumentation/index.ts+++ b/packages/shared/src/server/instrumentation/index.ts@@ -43,6 +43,14 @@ export async function instrumentAsync<T>(},activeContext,async (span) => {+ const baggage = opentelemetry.propagation.getBaggage(+ opentelemetry.context.active(),+ );+ if (baggage) {+ baggage+ .getAllEntries()+ .forEach(([k, v]) => span.setAttribute(k, v.value));+ }try {const result = await callback(span);span.end();@@ -77,6 +85,14 @@ export function instrumentSync<T>(},activeContext,(span) => {+ const baggage = opentelemetry.propagation.getBaggage(+ opentelemetry.context.active(),+ );+ if (baggage) {+ baggage+ .getAllEntries()+ .forEach(([k, v]) => span.setAttribute(k, v.value));+ }try {const result = callback(span);span.end();@@ -141,30 +157,6 @@ export const traceException = (});};-export const addUserToSpan = (- attributes: {- userId?: string;- projectId?: string;- email?: string;- orgId?: string;- plan?: string;- },- span?: opentelemetry.Span,-) => {- const activeSpan = span ?? getCurrentSpan();-- if (!activeSpan) {- return;- }-- attributes.userId && activeSpan.setAttribute("user.id", attributes.userId);- attributes.email && activeSpan.setAttribute("user.email", attributes.email);- attributes.projectId &&- activeSpan.setAttribute("project.id", attributes.projectId);- attributes.orgId && activeSpan.setAttribute("org.id", attributes.orgId);- attributes.plan && activeSpan.setAttribute("org.plan", attributes.plan);-};-export const getTracer = (name: string) => opentelemetry.trace.getTracer(name);const cloudWatchClient = new CloudWatchClient();diff --git a/packages/shared/src/server/logger.ts b/packages/shared/src/server/logger.tsindex ee990d48ee..664be2a1af 100644--- a/packages/shared/src/server/logger.ts+++ b/packages/shared/src/server/logger.ts@@ -1,6 +1,7 @@import { env } from "../env";import winston from "winston";import { getCurrentSpan } from "./instrumentation";+import { propagation, context } from "@opentelemetry/api";const tracingFormat = function () {return winston.format((info) => {@@ -13,6 +14,12 @@ const tracingFormat = function () {info["trace_id"] = traceId;info["span_id"] = spanId;}+ const baggage = propagation.getBaggage(context.active());+ if (baggage) {+ const headerObj: Record<string, string> = {};+ baggage.getAllEntries().forEach(([k, v]) => (headerObj[k] = v.value));+ if (Object.keys(headerObj).length) info = { ...headerObj, ...info };+ }return info;})();};diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 34d5602a16..8d95e4e998 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -1,6 +1,5 @@import { env } from "@/src/env.mjs";import {- addUserToSpan,createShaHash,recordIncrement,verifySecretKey,@@ -197,8 +196,6 @@ export class ApiAuthService {throw new Error("Invalid credentials");}- addUserToSpan({ projectId: finalApiKey.projectId ?? "" });-const plan = finalApiKey.plan;if (!isPlan(plan)) {@@ -235,8 +232,6 @@ export class ApiAuthService {);}- addUserToSpan({ projectId: dbKey.projectId ?? "" });-const { orgId, cloudConfig } =this.extractOrgIdAndCloudConfig(dbKey);@@ -277,14 +272,6 @@ export class ApiAuthService {};},);- // this adds the projectid to the root span of the request which makes it easier to find traces for specific projects- if (result.validKey && result.scope?.projectId) {- addUserToSpan({- projectId: result.scope.projectId,- orgId: result.scope.orgId,- plan: result.scope.plan,- });- }return result;}diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.tsindex 127fe32fdb..b05012ba8e 100644--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts@@ -10,6 +10,8 @@ import {} from "@langfuse/shared/src/server";import { type RateLimitResource } from "@langfuse/shared";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";+import { contextWithLangfuseProps } from "@langfuse/shared/src/server";+import * as opentelemetry from "@opentelemetry/api";import { env } from "@/src/env.mjs";type RouteConfig<@@ -89,26 +91,32 @@ export const createAuthedProjectAPIRoute = <? routeConfig.bodySchema.parse(req.body): {};- const response = await routeConfig.fn({- query,- body,- req,- res,- auth: auth as AuthHeaderValidVerificationResult & {- scope: { projectId: string; accessLevel: "project" };- },+ const ctx = contextWithLangfuseProps({+ headers: req.headers,+ projectId: auth.scope.projectId,});+ return opentelemetry.context.with(ctx, async () => {+ const response = await routeConfig.fn({+ query,+ body,+ req,+ res,+ auth: auth as AuthHeaderValidVerificationResult & {+ scope: { projectId: string; accessLevel: "project" };+ },+ });- if (env.NODE_ENV === "development" && routeConfig.responseSchema) {- const parsingResult = routeConfig.responseSchema.safeParse(response);- if (!parsingResult.success) {- logger.error("Response validation failed:", parsingResult.error);- traceException(parsingResult.error);+ if (env.NODE_ENV === "development" && routeConfig.responseSchema) {+ const parsingResult = routeConfig.responseSchema.safeParse(response);+ if (!parsingResult.success) {+ logger.error("Response validation failed:", parsingResult.error);+ traceException(parsingResult.error);+ }}- }- res- .status(routeConfig.successStatusCode || 200)- .json(response || { message: "OK" });+ res+ .status(routeConfig.successStatusCode || 200)+ .json(response || { message: "OK" });+ });};};diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex 3444c03139..3e2d5f09d7 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -6,6 +6,7 @@ import {redis,logger,getCurrentSpan,+ contextWithLangfuseProps,} from "@langfuse/shared/src/server";import { telemetry } from "@/src/features/telemetry";import { jsonSchema } from "@langfuse/shared";@@ -19,6 +20,7 @@ import { processEventBatch } from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";+import * as opentelemetry from "@opentelemetry/api";export const config = {api: {@@ -84,41 +86,50 @@ export default async function handler();}- try {- const rateLimitCheck =- await RateLimitService.getInstance().rateLimitRequest(- authCheck.scope,- "ingestion",- );-- if (rateLimitCheck?.isRateLimited()) {- return rateLimitCheck.sendRestResponseIfLimited(res);- }- } catch (e) {- // If rate-limiter returns an error, we log it and continue processing.- // This allows us to fail open instead of reject requests.- logger.error("Error while rate limiting", e);- }-- const batchType = z.object({- batch: z.array(z.unknown()),- metadata: jsonSchema.nullish(),+ const ctx = contextWithLangfuseProps({+ headers: req.headers,+ projectId: authCheck.scope.projectId,});+ // Execute the rest of the handler within the context+ return opentelemetry.context.with(ctx, async () => {+ try {+ const rateLimitCheck =+ await RateLimitService.getInstance().rateLimitRequest(+ authCheck.scope,+ "ingestion",+ );++ if (rateLimitCheck?.isRateLimited()) {+ return rateLimitCheck.sendRestResponseIfLimited(res);+ }+ } catch (e) {+ // If rate-limiter returns an error, we log it and continue processing.+ // This allows us to fail open instead of reject requests.+ logger.error("Error while rate limiting", e);+ }- const parsedSchema = batchType.safeParse(req.body);-- if (!parsedSchema.success) {- logger.info("Invalid request data", parsedSchema.error);- return res.status(400).json({- message: "Invalid request data",- errors: parsedSchema.error.issues.map((issue) => issue.message),+ const batchType = z.object({+ batch: z.array(z.unknown()),+ metadata: jsonSchema.nullish(),});- }- await telemetry();+ const parsedSchema = batchType.safeParse(req.body);- const result = await processEventBatch(parsedSchema.data.batch, authCheck);- return res.status(207).json(result);+ if (!parsedSchema.success) {+ logger.info("Invalid request data", parsedSchema.error);+ return res.status(400).json({+ message: "Invalid request data",+ errors: parsedSchema.error.issues.map((issue) => issue.message),+ });+ }++ await telemetry();+ const result = await processEventBatch(+ parsedSchema.data.batch,+ authCheck,+ );+ return res.status(207).json(result);+ });} catch (error: unknown) {if (!(error instanceof UnauthorizedError)) {logger.error("error_handling_ingestion_event", error);diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex 68db10f2d7..39f655d633 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -17,13 +17,16 @@import { type CreateNextContextOptions } from "@trpc/server/adapters/next";import { type Session } from "next-auth";import { tracing } from "@baselime/trpc-opentelemetry-middleware";-+import { contextWithLangfuseProps } from "@langfuse/shared/src/server";import { getServerAuthSession } from "@/src/server/auth";import { prisma, Role } from "@langfuse/shared/src/db";import * as z from "zod";+import * as opentelemetry from "@opentelemetry/api";+import { type IncomingHttpHeaders } from "node:http";type CreateContextOptions = {session: Session | null;+ headers: IncomingHttpHeaders;};/**@@ -39,6 +42,7 @@ type CreateContextOptions = {export const createInnerTRPCContext = (opts: CreateContextOptions) => {return {session: opts.session,+ headers: opts.headers,prisma,DB,};@@ -56,14 +60,10 @@ export const createTRPCContext = async (opts: CreateNextContextOptions) => {// Get the session from the server using the getServerSession wrapper functionconst session = await getServerAuthSession({ req, res });- addUserToSpan({- userId: session?.user?.id,- email: session?.user?.email ?? undefined,- });+ // Get the headers from the request+ const headers = req.headers;- return createInnerTRPCContext({- session,- });+ return createInnerTRPCContext({ session, headers });};/**@@ -78,11 +78,7 @@ import superjson from "superjson";import { ZodError } from "zod";import { setUpSuperjson } from "@/src/utils/superjson";import { DB } from "@/src/server/db";-import {- addUserToSpan,- getTraceById,- logger,-} from "@langfuse/shared/src/server";+import { getTraceById, logger } from "@langfuse/shared/src/server";setUpSuperjson();@@ -140,10 +136,22 @@ const withErrorHandling = t.middleware(async ({ ctx, next }) => {return res;});+// otel setup with proper context propagation+const withOtelInstrumentation = t.middleware(async (opts) => {+ const baggageCtx = contextWithLangfuseProps({+ headers: opts.ctx.headers,+ userId: opts.ctx.session?.user?.id,+ projectId: (opts.rawInput as Record<string, string>)?.projectId,+ });++ // Execute the next middleware/procedure with our context+ return opentelemetry.context.with(baggageCtx, () => opts.next());+});+// otel setup-const withOtelTracingProcedure = t.procedure.use(- tracing({ collectInput: true, collectResult: true }),-);+const withOtelTracingProcedure = t.procedure+ .use(withOtelInstrumentation)+ .use(tracing({ collectInput: true, collectResult: true }));/*** Public (unauthenticated) procedure