diff --git a/src/lib/formatters/local.ts b/src/lib/formatters/local.ts index bfa22b8d92..f99f2efe8e 100644 --- a/src/lib/formatters/local.ts +++ b/src/lib/formatters/local.ts @@ -125,6 +125,7 @@ const LEVEL_COLORS: Record string> = { error: (s) => red(bold(s)), fatal: (s) => red(bold(s)), warning: yellow, + warn: yellow, info: cyan, trace: green, debug: muted, @@ -157,6 +158,7 @@ const SERVER_JS_MARKERS = [ "astro", "nuxt", "sveltekit", + "cloudflare", ]; /** Source → color map for tail output. */ @@ -552,11 +554,133 @@ export function formatLogItem( return items.map((logEntry) => formatSingleLog(logEntry, source)); } +/** Shape of a single span in a standalone span envelope item (v2 span streaming). */ +export type StreamedSpan = { + trace_id?: string; + span_id?: string; + name?: string; + start_timestamp?: number; + end_timestamp?: number; + status?: string; + attributes?: Record; +}; + +/** + * Flatten typed span attributes (`{ key: { type, value } }`) into a plain + * `Record` compatible with the semantic display pipeline. + */ +function flattenSpanAttributes( + attrs: Record | undefined +): Record { + if (!attrs) { + return {}; + } + const flat: Record = {}; + for (const [key, entry] of Object.entries(attrs)) { + if (entry?.value !== undefined) { + flat[key] = entry.value; + } + } + return flat; +} + +/** + * Format a single standalone span into a colored one-liner, using the same + * semantic rendering as transactions. + */ +export function formatSingleSpan( + span: StreamedSpan, + header: Record +): string { + const spanName = sanitize(span.name ?? "unnamed span"); + const flat = flattenSpanAttributes(span.attributes); + const semantic = formatSemanticSpanDisplay(flat, spanName); + + let msg = sanitize(semantic.label); + if (semantic.metadata.length > 0) { + msg += ` ${semantic.metadata.map((m) => muted(`[${sanitize(m)}]`)).join(" ")}`; + } + + const semanticOp = inferSemanticOp(flat); + const op = + semanticOp ?? + (typeof flat["sentry.op"] === "string" + ? (flat["sentry.op"] as string) + : undefined); + if (op && op !== "default" && op !== "unknown") { + msg = `[${sanitize(op)}] ${msg}`; + } + + if (span.start_timestamp !== undefined && span.end_timestamp !== undefined) { + const durationMs = Math.round( + (span.end_timestamp - span.start_timestamp) * 1000 + ); + msg += ` ${muted(`[${durationMs}ms]`)}`; + } + + if (span.status && span.status !== "ok") { + msg += ` ${muted(`[${sanitize(span.status)}]`)}`; + } + + if (span.trace_id && TRACE_ID_RE.test(span.trace_id)) { + msg += ` ${muted(`[trace:${span.trace_id.toLowerCase().slice(0, TRACE_ID_SHORT_LEN)}]`)}`; + } + + const ts = formatTime(span.end_timestamp); + return `${muted(ts)} ${formatType("trace")} ${inferSource(header)} ${msg}`; +} + +/** + * Format a standalone span envelope item. A span item contains an `items` + * array of individual spans (v2 span streaming format); each gets its own line. + */ +export function formatSpanItem( + event: Record, + header: Record, + showAttributes = false +): string[] { + const items = event.items as StreamedSpan[] | undefined; + if (!items?.length) { + return []; + } + const lines: string[] = []; + for (const span of items) { + lines.push(formatSingleSpan(span, header)); + if (showAttributes) { + const flat = flattenSpanAttributes(span.attributes); + const table = formatAttributeTable({ + contexts: { trace: { data: flat } }, + }); + lines.push(...table); + } + } + return lines; +} + +/** + * Whether a standalone span item carries AI (GenAI/MCP) activity. + * Checks all spans in the container for AI-prefixed attributes. + */ +function spanItemHasAiActivity(payload: Record): boolean { + const items = payload.items as StreamedSpan[] | undefined; + if (!items?.length) { + return false; + } + for (const span of items) { + if (hasAiAttributes(flattenSpanAttributes(span.attributes))) { + return true; + } + } + return false; +} + /** Item types that map to the error formatter. */ export const ERROR_TYPES = new Set(["event", "error"]); /** * Map envelope item `type` to the corresponding `FilterValue`. + * Standalone `span` items map to `"transaction"` since they represent + * trace data (the same category transactions occupy). * Returns undefined for item types that don't map to a filter category. */ export function itemTypeToFilterCategory( @@ -568,8 +692,8 @@ export function itemTypeToFilterCategory( if (ERROR_TYPES.has(itemType)) { return "error"; } - if (itemType === "transaction" || itemType === "log") { - return itemType; + if (itemType === "transaction" || itemType === "span" || itemType === "log") { + return itemType === "span" ? "transaction" : itemType; } } @@ -732,6 +856,48 @@ function formatLogJson( ); } +/** Format a standalone span item as JSON objects (one per span). */ +function formatSpanJson( + payload: Record, + header: Record, + includeAttributes = false +): string[] { + const items = payload.items as StreamedSpan[] | undefined; + if (!items?.length) { + return []; + } + const source = inferSourceName(header); + return items.map((span) => { + const flat = flattenSpanAttributes(span.attributes); + const semantic = formatSemanticSpanDisplay( + flat, + span.name ?? "unnamed span" + ); + const durationMs = + span.start_timestamp !== undefined && span.end_timestamp !== undefined + ? Math.round((span.end_timestamp - span.start_timestamp) * 1000) + : undefined; + return JSON.stringify({ + type: "span", + timestamp: span.end_timestamp, + trace_id: span.trace_id, + span_id: span.span_id, + op: inferSemanticOp(flat) ?? flat["sentry.op"], + label: stripBidi(semantic.label), + metadata: + semantic.metadata.length > 0 + ? semantic.metadata.map(stripBidi) + : undefined, + duration_ms: durationMs, + status: span.status, + attributes: includeAttributes + ? buildJsonAttributes({ contexts: { trace: { data: flat } } }) + : undefined, + source, + }); + }); +} + /** * Format a single envelope item as a JSON line (NDJSON). * @@ -758,6 +924,9 @@ export function formatItemJson( if (itemType === "transaction") { return [formatTransactionJson(payload, header, showAttributes)]; } + if (itemType === "span") { + return formatSpanJson(payload, header, showAttributes); + } if (itemType === "log") { return formatLogJson(payload, header); } @@ -809,6 +978,9 @@ export function formatItem( } return lines; } + if (itemType === "span") { + return formatSpanItem(payload, header, showAttributes); + } if (itemType === "log") { return formatLogItem(payload, header); } @@ -833,9 +1005,14 @@ export function isItemIncluded( if (category !== undefined && activeFilters.has(category)) { return true; } - // The "ai" filter matches transactions with GenAI or MCP attributes. - if (activeFilters.has("ai") && itemType === "transaction" && payload) { - return transactionHasAiActivity(payload); + // The "ai" filter matches transactions and standalone spans with GenAI or MCP attributes. + if (activeFilters.has("ai") && payload) { + if (itemType === "transaction") { + return transactionHasAiActivity(payload); + } + if (itemType === "span") { + return spanItemHasAiActivity(payload); + } } return false; } diff --git a/test/lib/formatters/local.test.ts b/test/lib/formatters/local.test.ts index 574544274d..1f9f6d49ca 100644 --- a/test/lib/formatters/local.test.ts +++ b/test/lib/formatters/local.test.ts @@ -15,6 +15,8 @@ import { formatItem, formatItemJson, formatSingleLog, + formatSingleSpan, + formatSpanItem, formatTime, formatTransactionItem, inferSource, @@ -1020,3 +1022,169 @@ describe("formatItem with attributes", () => { expect(lines).toHaveLength(1); }); }); + +describe("standalone span support", () => { + const cfHeader = { sdk: { name: "sentry.javascript.cloudflare" } }; + + const aiSpan = { + trace_id: "a".repeat(32), + span_id: "b".repeat(16), + name: "chat anthropic/claude-4-sonnet", + start_timestamp: 1_700_000_000, + end_timestamp: 1_700_000_001.2, + status: "ok", + attributes: { + "gen_ai.system": { type: "string", value: "anthropic" }, + "gen_ai.request.model": { type: "string", value: "claude-4-sonnet" }, + "gen_ai.usage.input_tokens": { type: "integer", value: 512 }, + "gen_ai.usage.output_tokens": { type: "integer", value: 128 }, + "sentry.op": { type: "string", value: "gen_ai.chat" }, + }, + }; + + const mcpSpan = { + trace_id: "c".repeat(32), + span_id: "d".repeat(16), + name: "tools/call list_files", + start_timestamp: 1_700_000_000, + end_timestamp: 1_700_000_000.4, + status: "ok", + attributes: { + "mcp.method.name": { type: "string", value: "tools/call" }, + "mcp.tool.name": { type: "string", value: "list_files" }, + "sentry.op": { type: "string", value: "mcp.server" }, + }, + }; + + describe("formatSingleSpan", () => { + test("formats a gen_ai span with semantic labels", () => { + const line = stripAnsi(formatSingleSpan(aiSpan, cfHeader)); + expect(line).toContain("[gen_ai"); + expect(line).toContain("claude-4-sonnet"); + expect(line).toContain("[1200ms]"); + expect(line).toContain("[trace:aaaaaaaa]"); + expect(line).toContain("[SERVER]"); + }); + + test("formats an MCP span", () => { + const line = stripAnsi(formatSingleSpan(mcpSpan, cfHeader)); + expect(line).toContain("mcp"); + expect(line).toContain("tools/call"); + expect(line).toContain("[400ms]"); + }); + + test("handles missing name gracefully", () => { + const span = { + trace_id: "a".repeat(32), + start_timestamp: 1_700_000_000, + end_timestamp: 1_700_000_000.5, + status: "ok", + attributes: { + "http.method": { type: "string", value: "GET" }, + }, + }; + const line = stripAnsi(formatSingleSpan(span, cfHeader)); + expect(line).toContain("[TRACE]"); + expect(line).toContain("[SERVER]"); + expect(line).toContain("[500ms]"); + }); + }); + + describe("formatSpanItem", () => { + test("formats each span in the container", () => { + const payload = { items: [aiSpan, mcpSpan] }; + const lines = formatSpanItem(payload, cfHeader); + expect(lines).toHaveLength(2); + expect(stripAnsi(lines[0]!)).toContain("gen_ai"); + expect(stripAnsi(lines[1]!)).toContain("mcp"); + }); + + test("returns empty for missing items", () => { + expect(formatSpanItem({}, cfHeader)).toHaveLength(0); + expect(formatSpanItem({ items: [] }, cfHeader)).toHaveLength(0); + }); + }); + + describe("formatItem routes span type", () => { + test("routes span items to span formatter", () => { + const payload = { items: [aiSpan] }; + const lines = formatItem("span", payload, cfHeader, "span"); + expect(lines.length).toBeGreaterThanOrEqual(1); + expect(stripAnsi(lines[0]!)).toContain("gen_ai"); + }); + }); + + describe("formatItemJson routes span type", () => { + test("produces structured JSON for standalone spans", () => { + const payload = { items: [aiSpan] }; + const lines = formatItemJson("span", payload, cfHeader); + expect(lines).toHaveLength(1); + const parsed = JSON.parse(lines[0]!); + expect(parsed.type).toBe("span"); + expect(parsed.trace_id).toBe("a".repeat(32)); + expect(parsed.span_id).toBe("b".repeat(16)); + expect(parsed.op).toBe("gen_ai.chat"); + expect(parsed.duration_ms).toBe(1200); + expect(parsed.source).toBe("server"); + }); + }); + + describe("itemTypeToFilterCategory maps span to transaction", () => { + test("maps span to transaction category", () => { + expect(itemTypeToFilterCategory("span")).toBe("transaction"); + }); + }); + + describe("isItemIncluded handles standalone spans", () => { + test("ai filter matches span items with gen_ai attributes", () => { + const filters = new Set(["ai"]); + const payload = { items: [aiSpan] }; + expect(isItemIncluded("span", filters, payload)).toBe(true); + }); + + test("ai filter matches span items with mcp attributes", () => { + const filters = new Set(["ai"]); + const payload = { items: [mcpSpan] }; + expect(isItemIncluded("span", filters, payload)).toBe(true); + }); + + test("ai filter does not match span items without ai attributes", () => { + const filters = new Set(["ai"]); + const plainSpan = { + ...aiSpan, + attributes: { + "http.method": { type: "string", value: "GET" }, + }, + }; + const payload = { items: [plainSpan] }; + expect(isItemIncluded("span", filters, payload)).toBe(false); + }); + + test("transaction filter matches standalone spans", () => { + const filters = new Set(["transaction"]); + const payload = { items: [aiSpan] }; + expect(isItemIncluded("span", filters, payload)).toBe(true); + }); + }); +}); + +describe("inferSource cloudflare SDK", () => { + test("detects Cloudflare Workers SDK as server", () => { + const result = stripAnsi( + inferSource({ sdk: { name: "sentry.javascript.cloudflare" } }) + ); + expect(result).toContain("[SERVER]"); + }); +}); + +describe("warn level coloring", () => { + test("warn level gets formatted with brackets", () => { + const log = { + level: "warn", + body: "Rate limit approaching", + timestamp: 1_700_000_000, + }; + const result = formatSingleLog(log, "[SERVER] "); + expect(stripAnsi(result)).toContain("[WARN]"); + }); +});