UNPKG

@fiberplane/hono-otel

Version:

Hono middleware to forward OpenTelemetry traces to a local instance of @fiberplane/studio

35 lines (34 loc) 1.71 kB
import { SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH, SEMATTRS_HTTP_SCHEME, } from "@opentelemetry/semantic-conventions"; import { getFpResolvedConfig, getShouldTraceEverything, } from "../../config/index.js"; import { EXTRA_SEMATTRS_HTTP_RESPONSE_STATUS_CODE, FPX_RESPONSE_BODY, } from "../../constants.js"; import { getLogger } from "../../logger.js"; import { tryGetResponseBodyAsText } from "./body.js"; import { getSafeHeaderValue, headersToObject } from "./headers.js"; export async function getResponseAttributes(response, config) { const resolvedConfig = config ?? getFpResolvedConfig(); const shouldTraceEverything = getShouldTraceEverything(resolvedConfig); const logger = getLogger(resolvedConfig?.logLevel ?? "debug"); if (!resolvedConfig) { logger.debug("[getResponseAttributes] No config found in otel context, using default values"); } const attributes = { [EXTRA_SEMATTRS_HTTP_RESPONSE_STATUS_CODE]: String(response.status), [SEMATTRS_HTTP_SCHEME]: response.url.split(":")[0], }; if (shouldTraceEverything) { const responseText = await tryGetResponseBodyAsText(response); if (responseText) { attributes[FPX_RESPONSE_BODY] = responseText; } } const contentLength = response.headers.get("content-length"); if (contentLength) { attributes[SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH] = contentLength; } const headers = response.headers; const responseHeaders = headersToObject(headers); for (const [key, value] of Object.entries(responseHeaders)) { attributes[`http.response.header.${key}`] = getSafeHeaderValue(key, value, resolvedConfig); } return attributes; }