diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index 9db9ec7ab..848beae7f 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -129,7 +129,7 @@ By default, incoming envelopes are pretty-printed to the terminal: 14:32:04 [WARNING] [BROWSER] Cart is empty [page.tsx:24:19] [onClick] ``` -Errors show their level, the exception type, message, and the newest stack frame from your app. Messages, such as `captureMessage` calls and Python `logging` records, show their level and text, plus the logger name when there is one. Transactions show the operation, duration, and span count. Logs show the severity level, message, and custom attributes. Attributes the SDK adds itself (`sentry.`, `http.`, `url.`, `db.`, `server.`, `code.`, `thread.`, `logger.`, `user.`, and similar prefixes, plus Python's `asctime` and Django's `request` and `server_time`) are hidden; add `--attributes` (`-a`) to list them under each log line. +Errors show their level, the exception type, message, and the newest stack frame from your app. Messages, such as `captureMessage` calls and Python `logging` records, show their level and text, plus the logger name when there is one. Transactions show the operation, duration, and span count. Logs show the severity level, message, and custom attributes. Attributes the SDK adds itself are hidden: `sentry.`, `http.`, `url.`, `db.`, `server.`, `code.`, `thread.`, `logger.`, and similar prefixes, the scope user (`user.id`, `user.email`, `user.name`, `user.username`, `user.ip_address`), Python's `asctime`, `request` and `server_time`, Rust's `os.name`, `os.version` and `parent_span_id`, and Ruby's `parameters`. Your own attributes, such as `user.plan`, still show. Add `--attributes` (`-a`) to list the hidden ones under each log line. Events and logs use the same labels: a warning is `[WARNING]` whether the SDK sent `warning` or `warn`, and an event's logger shows as `[logger:name]`. A log's logger name is an SDK attribute, so it shows only with `-a`. diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md index 673d9ebaf..b648fa4bc 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md @@ -82,7 +82,7 @@ Start the local dev server and tail events - `-q, --quiet - Suppress per-envelope tail output` - `-f, --filter ... - Only show items of this type (repeatable: error, transaction, log, ai)` - `-F, --format - Output format: human (default) or json (NDJSON on stdout) - (default: "human")` -- `-a, --attributes - Also show SDK attributes, under each transaction and log or in JSON` +- `-a, --attributes - Also show SDK attributes, under each transaction, span and log or in JSON` - `--open - Open Sentry Local UI in the browser` - `--max-envelopes - Maximum envelopes retained by this receiver or session` - `--session - Create a daemon-owned telemetry session with this label` @@ -195,7 +195,7 @@ Run a command with the local dev server enabled - `-V, --verify - Verify SDK sends events, then exit` - `-t, --timeout - Kill the child after N seconds (0 = no timeout; defaults to 30 s in --verify mode) - (default: "0")` - `-F, --format - Output format: human (default) or json (NDJSON on stdout) - (default: "human")` -- `-a, --attributes - Also show SDK attributes, under each transaction and log or in JSON` +- `-a, --attributes - Also show SDK attributes, under each transaction, span and log or in JSON` - `--open - Open Sentry Local UI in the browser` - `--max-envelopes - Maximum envelopes retained by this receiver or session` - `--session - Create a daemon-owned telemetry session with this label` diff --git a/packages/cli/src/commands/local/event-summary.ts b/packages/cli/src/commands/local/event-summary.ts index 61585883a..835c11910 100644 --- a/packages/cli/src/commands/local/event-summary.ts +++ b/packages/cli/src/commands/local/event-summary.ts @@ -42,16 +42,8 @@ const TRACE_ID_RE = /^[0-9a-f]{32}$/i; /** Longest title kept in a summary; longer ones end in `…`. */ const MAX_TITLE_LENGTH = 200; -/** Log levels from least to most severe; logs send `warn`, events `warning`. */ -const LOG_LEVEL_ORDER = [ - "trace", - "debug", - "info", - "warn", - "warning", - "error", - "fatal", -]; +/** Log levels from least to most severe. */ +const LOG_LEVEL_ORDER = ["trace", "debug", "info", "warning", "error", "fatal"]; function record(value: unknown): Record { return value !== null && typeof value === "object" && !Array.isArray(value) @@ -109,11 +101,16 @@ function logTraceId(log: Record): string | undefined { ); } -/** Severity rank of a log level; unknown levels rank lowest. */ +/** + * Severity rank of a log level; unknown levels rank lowest. Logs send `warn` + * and events send `warning`; both rank the same. + */ function levelRank(level: unknown): number { - return typeof level === "string" - ? LOG_LEVEL_ORDER.indexOf(level.toLowerCase()) - : -1; + if (typeof level !== "string") { + return -1; + } + const lower = level.toLowerCase(); + return LOG_LEVEL_ORDER.indexOf(lower === "warn" ? "warning" : lower); } /** The first log with the batch's most severe level. */ diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index ba7bc1554..0126ca3de 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -566,7 +566,7 @@ export const runCommand = buildCommand({ attributes: { kind: "boolean", brief: - "Also show SDK attributes, under each transaction and log or in JSON", + "Also show SDK attributes, under each transaction, span and log or in JSON", default: false, }, open: { diff --git a/packages/cli/src/commands/local/server.ts b/packages/cli/src/commands/local/server.ts index 625baabf7..5ea0ea31b 100644 --- a/packages/cli/src/commands/local/server.ts +++ b/packages/cli/src/commands/local/server.ts @@ -1246,7 +1246,7 @@ export const serverCommand = buildCommand({ attributes: { kind: "boolean", brief: - "Also show SDK attributes, under each transaction and log or in JSON", + "Also show SDK attributes, under each transaction, span and log or in JSON", default: false, }, open: { diff --git a/packages/cli/src/lib/formatters/local.ts b/packages/cli/src/lib/formatters/local.ts index 1bce2e46b..05705612e 100644 --- a/packages/cli/src/lib/formatters/local.ts +++ b/packages/cli/src/lib/formatters/local.ts @@ -539,16 +539,40 @@ const SDK_ATTRIBUTE_PREFIXES = [ "exception.", "error.", "user_agent.", - "logger.", - "user.", ]; /** - * Exact keys that SDK logging integrations add, such as the Python `logging` - * record's `asctime` and the `request` and `server_time` extras that Django's - * dev server sets on every access log. + * Exact log attribute keys that SDKs add on their own: the scope user they + * copy onto every log, the Python `logging` record's `asctime`, and the + * `server_time` extra that Django's dev server sets on access logs. */ -const SDK_ATTRIBUTE_KEYS = new Set(["asctime", "request", "server_time"]); +const SDK_LOG_ATTRIBUTE_KEYS = new Set([ + "user.id", + "user.email", + "user.name", + "user.username", + "user.ip_address", + "asctime", + "server_time", +]); + +/** + * Log attribute keys that one SDK adds, keyed by its `sentry.sdk.name` + * prefix. Other SDKs leave these names free for custom attributes. + * sentry-rust adds the OS and the active span; sentry-ruby keeps the + * `parameters:` argument of `Sentry.logger.info` as an attribute. + */ +const SDK_LOG_ATTRIBUTE_KEYS_BY_SDK: readonly [string, ReadonlySet][] = + [ + ["sentry.rust", new Set(["os.name", "os.version", "parent_span_id"])], + ["sentry.ruby", new Set(["parameters"])], + ]; + +/** + * A `request` value that is an object repr, like the socket or + * `WSGIRequest` that Python's `logging` extras put on access logs. + */ +const REQUEST_REPR_RE = /^<(?:WSGIRequest|ASGIRequest|socket)\b/; /** Two-space indent prefix for nested attribute-table lines. */ const ATTR_INDENT = " "; @@ -560,9 +584,37 @@ const ATTR_INDENT = " "; */ function isSdkAttribute(key: string): boolean { const lower = key.toLowerCase(); - return ( - SDK_ATTRIBUTE_KEYS.has(lower) || - SDK_ATTRIBUTE_PREFIXES.some((prefix) => lower.startsWith(prefix)) + return SDK_ATTRIBUTE_PREFIXES.some((prefix) => lower.startsWith(prefix)); +} + +/** + * Whether a log attribute was added by the SDK rather than the app. Adds the + * log-only keys, such as `logger.*` from logging integrations, to + * {@link isSdkAttribute}; on a span the same keys are custom. A bare `request` counts only when + * the SDK is Python or the value is an object repr, so an app's own + * `request` attribute still shows. + */ +function isSdkLogAttribute( + key: string, + value: unknown, + sdkName: string, +): boolean { + const lower = key.toLowerCase(); + if ( + isSdkAttribute(key) || + SDK_LOG_ATTRIBUTE_KEYS.has(lower) || + lower.startsWith("logger.") + ) { + return true; + } + if (lower === "request") { + return ( + sdkName.startsWith("sentry.python") || + (typeof value === "string" && REQUEST_REPR_RE.test(value)) + ); + } + return SDK_LOG_ATTRIBUTE_KEYS_BY_SDK.some( + ([sdk, keys]) => sdkName.startsWith(sdk) && keys.has(lower), ); } @@ -681,6 +733,27 @@ function logAttributeEntries(logEntry: LogEntry): [string, unknown][] { .map(([k, v]) => [k, v.value]); } +/** + * Split a log's attributes into the app's own and the SDK's, by + * {@link isSdkLogAttribute}. The SDK name comes from the log's + * `sentry.sdk.name`, else the envelope header. + */ +function splitLogAttributes( + logEntry: LogEntry, + header: Record, +): { custom: [string, unknown][]; sdk: [string, unknown][] } { + const fromLog = logEntry.attributes?.["sentry.sdk.name"]?.value; + const fromHeader = (header["sdk"] as { name?: unknown } | undefined)?.name; + const name = fromLog ?? fromHeader; + const sdkName = typeof name === "string" ? name : ""; + const custom: [string, unknown][] = []; + const sdk: [string, unknown][] = []; + for (const entry of logAttributeEntries(logEntry)) { + (isSdkLogAttribute(entry[0], entry[1], sdkName) ? sdk : custom).push(entry); + } + return { custom, sdk }; +} + /** * Extract the trace ID from a log entry's attributes. * @@ -701,18 +774,20 @@ function extractLogTraceId(logEntry: LogEntry): string | undefined { * * User-supplied attributes are rendered alphabetically by key so repeated log * lines align column-for-column and are easy to scan. SDK-default attributes - * (`sentry.*`, `code.*`, `logger.*`, `user.*`, … see - * {@link SDK_ATTRIBUTE_PREFIXES} and {@link SDK_ATTRIBUTE_KEYS}) are omitted - * from the inline list; the trace ID is surfaced as a compact `[trace:…]` - * token instead. + * (`sentry.*`, `code.*`, `logger.*`, the scope user, … see + * {@link isSdkLogAttribute}) are omitted from the inline list; the trace ID + * is surfaced as a compact `[trace:…]` token instead. */ -export function formatSingleLog(logEntry: LogEntry, source: string): string { +export function formatSingleLog( + logEntry: LogEntry, + source: string, + header: Record = {}, +): string { const level = logEntry.level ?? "log"; let msg = sanitize(logEntry.body ?? ""); - const attrs = logAttributeEntries(logEntry) - .filter(([k]) => !isSdkAttribute(k)) - .sort(([a], [b]) => a.localeCompare(b)) + const attrs = splitLogAttributes(logEntry, header) + .custom.sort(([a], [b]) => a.localeCompare(b)) .map(([k, v]) => muted(`[${sanitize(k)}=${sanitize(String(v))}]`)); if (attrs.length > 0) { msg += ` ${attrs.join(" ")}`; @@ -749,13 +824,11 @@ export function formatLogItem( // One log batch comes from one SDK client, so any browser log places all. const source = inferSource(header, undefined, items.map(logAttributes)); return items.flatMap((logEntry) => { - const line = formatSingleLog(logEntry, source); + const line = formatSingleLog(logEntry, source, header); if (!showAttributes) { return [line]; } - const sdk = logAttributeEntries(logEntry).filter(([k]) => - isSdkAttribute(k), - ); + const { sdk } = splitLogAttributes(logEntry, header); return [line, ...formatAttrGroup("sdk attributes", sdk)]; }); } @@ -1297,20 +1370,7 @@ function formatLogJson( level: entry.level ?? "log", message: stripBidi(entry.body ?? ""), attributes: entry.attributes - ? Object.fromEntries( - Object.entries(entry.attributes) - .filter( - ([k, v]) => - isUserLogAttribute(k) && - (includeAttributes || !isSdkAttribute(k)) && - v.value !== null && - v.value !== undefined, - ) - .map(([k, v]) => [ - stripBidi(k), - typeof v.value === "string" ? stripBidi(v.value) : v.value, - ]), - ) + ? jsonLogAttributes(entry, header, includeAttributes) : undefined, source, }, @@ -1320,6 +1380,22 @@ function formatLogJson( ); } +/** + * A log's attributes for its JSON record: the custom ones, plus the SDK ones + * (except `sentry.*`) when `includeAttributes` is true. + */ +function jsonLogAttributes( + entry: LogEntry, + header: Record, + includeAttributes: boolean, +): Record { + const { custom, sdk } = splitLogAttributes(entry, header); + const entries = includeAttributes + ? [...custom, ...sdk.filter(([k]) => isUserLogAttribute(k))] + : custom; + return Object.fromEntries(entries); +} + /** Format a standalone span item as JSON objects (one per span). */ function formatSpanJson( payload: Record, diff --git a/packages/cli/test/commands/local/event-summary.test.ts b/packages/cli/test/commands/local/event-summary.test.ts index ba0e51fca..7af529a32 100644 --- a/packages/cli/test/commands/local/event-summary.test.ts +++ b/packages/cli/test/commands/local/event-summary.test.ts @@ -173,6 +173,17 @@ describe("summarizeEnvelope", () => { }); }); + test("ranks warn and warning logs the same", () => { + expect( + summarize("log", { + items: [ + { level: "warn", body: "Retrying", timestamp: 1_794_947_106 }, + { level: "warning", body: "Disk low", timestamp: 1_794_947_107 }, + ], + }).title, + ).toBe("Retrying"); + }); + test("titles session aggregates like the viewer", () => { expect( summarize("sessions", { diff --git a/packages/cli/test/lib/formatters/local-sdk-events.test.ts b/packages/cli/test/lib/formatters/local-sdk-events.test.ts index 584275cd0..d3bbaa48b 100644 --- a/packages/cli/test/lib/formatters/local-sdk-events.test.ts +++ b/packages/cli/test/lib/formatters/local-sdk-events.test.ts @@ -7,6 +7,7 @@ import { describe, expect, test } from "vitest"; import { + formatAttributeTable, formatItem, formatItemJson, } from "../../../src/lib/formatters/local.js"; @@ -557,6 +558,132 @@ describe("log attributes", () => { }); }); +describe("SDK log attributes stay log-only", () => { + /** One log item from the given SDK with the given attributes. */ + function sdkLog( + sdkName: string, + attributes: Record, + ): Record { + return { + items: [ + { + timestamp: 1_794_045_606.1, + level: "info", + body: "Checkout done", + attributes: Object.fromEntries( + Object.entries({ "sentry.sdk.name": sdkName, ...attributes }).map( + ([key, value]) => [key, { value }], + ), + ), + }, + ], + }; + } + + /** The tail line for one log item, without colors. */ + function logLine(sdkName: string, attributes: Record) { + const header = { sdk: { name: sdkName, version: "1.0.0" } }; + const lines = formatItem("log", sdkLog(sdkName, attributes), header, "log"); + return stripAnsi(lines[0] ?? ""); + } + + test("custom user.* attributes stay on the line", () => { + const line = logLine("sentry.python.flask", { + "user.id": "42", + "user.plan": "pro", + }); + expect(line).toContain("[user.plan=pro]"); + expect(line).not.toContain("user.id"); + }); + + test("a bare request is hidden only when it is an SDK repr", () => { + expect( + logLine("sentry.javascript.node", { request: "checkout" }), + ).toContain("[request=checkout]"); + expect( + logLine("sentry.javascript.node", { + request: "", + }), + ).not.toContain("request="); + }); + + test("Rust log attributes are hidden without --attributes", () => { + const attributes = { + "os.name": "macos", + "os.version": "15.1", + parent_span_id: "b0e6f15b45c36b12", + order_id: "o-1", + }; + const line = logLine("sentry.rust", attributes); + expect(line).toContain("[order_id=o-1]"); + for (const key of ["os.name", "os.version", "parent_span_id"]) { + expect(line).not.toContain(key); + } + // Other SDKs keep the same keys as custom attributes. + expect(logLine("sentry.javascript.node", attributes)).toContain( + "[os.name=macos]", + ); + + const header = { sdk: { name: "sentry.rust", version: "0.40.0" } }; + const table = formatItem( + "log", + sdkLog("sentry.rust", attributes), + header, + "log", + true, + ) + .map(stripAnsi) + .slice(1) + .join("\n"); + expect(table).toContain("os.name"); + expect(table).toContain("parent_span_id"); + }); + + test("Ruby's parameters attribute is hidden without --attributes", () => { + const line = logLine("sentry.ruby.rails", { + parameters: '["jane"]', + "sentry.message.parameter.0": "jane", + order_id: "o-1", + }); + expect(line).toContain("[order_id=o-1]"); + expect(line).not.toContain("parameters"); + }); + + test("transactions keep log-only keys as custom attributes", () => { + const data = { + asctime: "2026-11-17 10:00:06,101", + "logger.name": "app", + request: "checkout", + server_time: "10:00:06", + "user.email": "jane@example.com", + "http.method": "GET", + }; + const event = { + timestamp: 1_794_045_606.2, + start_timestamp: 1_794_045_606.1, + contexts: { trace: { op: "http.server", data } }, + }; + const header = { sdk: { name: "sentry.python.flask", version: "2.42.0" } }; + const [line] = formatItemJson("transaction", event, header, true); + const record = JSON.parse(line ?? "{}") as { + attributes: Record>; + }; + expect(Object.keys(record.attributes["user"] ?? {}).sort()).toEqual([ + "asctime", + "logger.name", + "request", + "server_time", + "user.email", + ]); + expect(record.attributes["sdk"]).toEqual({ "http.method": "GET" }); + + const table = formatAttributeTable(event).map(stripAnsi).join("\n"); + const userGroup = table.slice(0, table.indexOf("sdk attributes")); + expect(userGroup).toContain("user.email"); + expect(userGroup).toContain("asctime"); + }); +}); + describe("colored log text", () => { /** A uvicorn access log whose formatter colored the message. */ const uvicornLog = {