Skip to content

Commit 9532d29

Browse files
fix(cli): Keep SDK log attributes log-only in sentry local (#2394)
Follow-up to #2369 and #2377. The keys we started hiding on log lines (`user.*`, `asctime`, `request`, `server_time`, `logger.*`) were also applied to transactions and spans. So `-a` moved a span's `user.email` into the `sdk` group. They now only apply to logs. Other small fixes: - Only the user fields the SDK copies onto logs are hidden (`user.id`, `user.email`, `user.name`, `user.username`, `user.ip_address`). Your own `user.plan` still shows. - A bare `request` is hidden only on Python logs, or when it's an object repr like `<WSGIRequest …>`. - Rust logs hide `os.name`, `os.version` and `parent_span_id`. Ruby logs hide `parameters`. Other SDKs keep those as normal attributes. - `event list` ranks `warn` and `warning` logs the same. - The `-a` help now says "transaction, span and log". Before: ``` 10:00:06 [INFO] [SERVER] Checkout done [os.name=macos] [os.version=15.1] [order_id=o-1] [parent_span_id=b0e6f15b45c36b12] {"type":"transaction",...,"attributes":{"sdk":{"user.email":"jane@example.com","asctime":"..."}}} ``` After: ``` 10:00:06 [INFO] [SERVER] Checkout done [order_id=o-1] {"type":"transaction",...,"attributes":{"user":{"user.email":"jane@example.com","asctime":"..."}}} ``` <!-- junior-request-attribution:start --> via @MathurAditya724. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3Af689f1f928b25c03737a6ea9643eadc2 --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3Af689f1f928b25c03737a6ea9643eadc2) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3Af689f1f928b25c03737a6ea9643eadc2/?project=4510944073809921) <!-- junior-session-footer:end --> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com>
1 parent 3a73268 commit 9532d29

8 files changed

Lines changed: 265 additions & 54 deletions

File tree

‎apps/cli-docs/src/fragments/commands/local.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ By default, incoming envelopes are pretty-printed to the terminal:
155155
14:32:04 [WARNING] [BROWSER] Cart is empty [page.tsx:24:19] [onClick]
156156
```
157157

158-
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.
158+
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.
159159

160160
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`.
161161

‎packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ Start the local dev server and tail events
8282
- `-q, --quiet - Suppress per-envelope tail output`
8383
- `-f, --filter <value>... - Only show items of this type (repeatable: error, transaction, log, ai)`
8484
- `-F, --format <value> - Output format: human (default) or json (NDJSON on stdout) - (default: "human")`
85-
- `-a, --attributes - Also show SDK attributes, under each transaction and log or in JSON`
85+
- `-a, --attributes - Also show SDK attributes, under each transaction, span and log or in JSON`
8686
- `--open - Open Sentry Local UI in the browser`
8787
- `--max-envelopes <value> - Maximum envelopes retained by this receiver or session`
8888
- `--session <value> - Create a daemon-owned telemetry session with this label`
@@ -195,7 +195,7 @@ Run a command with the local dev server enabled
195195
- `-V, --verify - Verify SDK sends events, then exit`
196196
- `-t, --timeout <value> - Kill the child after N seconds (0 = no timeout; defaults to 30 s in --verify mode) - (default: "0")`
197197
- `-F, --format <value> - Output format: human (default) or json (NDJSON on stdout) - (default: "human")`
198-
- `-a, --attributes - Also show SDK attributes, under each transaction and log or in JSON`
198+
- `-a, --attributes - Also show SDK attributes, under each transaction, span and log or in JSON`
199199
- `--open - Open Sentry Local UI in the browser`
200200
- `--max-envelopes <value> - Maximum envelopes retained by this receiver or session`
201201
- `--session <value> - Create a daemon-owned telemetry session with this label`

‎packages/cli/src/commands/local/event-summary.ts‎

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,8 @@ const TRACE_ID_RE = /^[0-9a-f]{32}$/i;
4242
/** Longest title kept in a summary; longer ones end in `…`. */
4343
const MAX_TITLE_LENGTH = 200;
4444

45-
/** Log levels from least to most severe; logs send `warn`, events `warning`. */
46-
const LOG_LEVEL_ORDER = [
47-
"trace",
48-
"debug",
49-
"info",
50-
"warn",
51-
"warning",
52-
"error",
53-
"fatal",
54-
];
45+
/** Log levels from least to most severe. */
46+
const LOG_LEVEL_ORDER = ["trace", "debug", "info", "warning", "error", "fatal"];
5547

5648
function record(value: unknown): Record<string, unknown> {
5749
return value !== null && typeof value === "object" && !Array.isArray(value)
@@ -109,11 +101,16 @@ function logTraceId(log: Record<string, unknown>): string | undefined {
109101
);
110102
}
111103

112-
/** Severity rank of a log level; unknown levels rank lowest. */
104+
/**
105+
* Severity rank of a log level; unknown levels rank lowest. Logs send `warn`
106+
* and events send `warning`; both rank the same.
107+
*/
113108
function levelRank(level: unknown): number {
114-
return typeof level === "string"
115-
? LOG_LEVEL_ORDER.indexOf(level.toLowerCase())
116-
: -1;
109+
if (typeof level !== "string") {
110+
return -1;
111+
}
112+
const lower = level.toLowerCase();
113+
return LOG_LEVEL_ORDER.indexOf(lower === "warn" ? "warning" : lower);
117114
}
118115

119116
/** The first log with the batch's most severe level. */

‎packages/cli/src/commands/local/run.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -574,7 +574,7 @@ export const runCommand = buildCommand({
574574
attributes: {
575575
kind: "boolean",
576576
brief:
577-
"Also show SDK attributes, under each transaction and log or in JSON",
577+
"Also show SDK attributes, under each transaction, span and log or in JSON",
578578
default: false,
579579
},
580580
open: {

‎packages/cli/src/commands/local/server.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1246,7 +1246,7 @@ export const serverCommand = buildCommand({
12461246
attributes: {
12471247
kind: "boolean",
12481248
brief:
1249-
"Also show SDK attributes, under each transaction and log or in JSON",
1249+
"Also show SDK attributes, under each transaction, span and log or in JSON",
12501250
default: false,
12511251
},
12521252
open: {

‎packages/cli/src/lib/formatters/local.ts‎

Lines changed: 111 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -539,16 +539,40 @@ const SDK_ATTRIBUTE_PREFIXES = [
539539
"exception.",
540540
"error.",
541541
"user_agent.",
542-
"logger.",
543-
"user.",
544542
];
545543

546544
/**
547-
* Exact keys that SDK logging integrations add, such as the Python `logging`
548-
* record's `asctime` and the `request` and `server_time` extras that Django's
549-
* dev server sets on every access log.
545+
* Exact log attribute keys that SDKs add on their own: the scope user they
546+
* copy onto every log, the Python `logging` record's `asctime`, and the
547+
* `server_time` extra that Django's dev server sets on access logs.
550548
*/
551-
const SDK_ATTRIBUTE_KEYS = new Set(["asctime", "request", "server_time"]);
549+
const SDK_LOG_ATTRIBUTE_KEYS = new Set([
550+
"user.id",
551+
"user.email",
552+
"user.name",
553+
"user.username",
554+
"user.ip_address",
555+
"asctime",
556+
"server_time",
557+
]);
558+
559+
/**
560+
* Log attribute keys that one SDK adds, keyed by its `sentry.sdk.name`
561+
* prefix. Other SDKs leave these names free for custom attributes.
562+
* sentry-rust adds the OS and the active span; sentry-ruby keeps the
563+
* `parameters:` argument of `Sentry.logger.info` as an attribute.
564+
*/
565+
const SDK_LOG_ATTRIBUTE_KEYS_BY_SDK: readonly [string, ReadonlySet<string>][] =
566+
[
567+
["sentry.rust", new Set(["os.name", "os.version", "parent_span_id"])],
568+
["sentry.ruby", new Set(["parameters"])],
569+
];
570+
571+
/**
572+
* A `request` value that is an object repr, like the socket or
573+
* `WSGIRequest` that Python's `logging` extras put on access logs.
574+
*/
575+
const REQUEST_REPR_RE = /^<(?:WSGIRequest|ASGIRequest|socket)\b/;
552576

553577
/** Two-space indent prefix for nested attribute-table lines. */
554578
const ATTR_INDENT = " ";
@@ -560,9 +584,37 @@ const ATTR_INDENT = " ";
560584
*/
561585
function isSdkAttribute(key: string): boolean {
562586
const lower = key.toLowerCase();
563-
return (
564-
SDK_ATTRIBUTE_KEYS.has(lower) ||
565-
SDK_ATTRIBUTE_PREFIXES.some((prefix) => lower.startsWith(prefix))
587+
return SDK_ATTRIBUTE_PREFIXES.some((prefix) => lower.startsWith(prefix));
588+
}
589+
590+
/**
591+
* Whether a log attribute was added by the SDK rather than the app. Adds the
592+
* log-only keys, such as `logger.*` from logging integrations, to
593+
* {@link isSdkAttribute}; on a span the same keys are custom. A bare `request` counts only when
594+
* the SDK is Python or the value is an object repr, so an app's own
595+
* `request` attribute still shows.
596+
*/
597+
function isSdkLogAttribute(
598+
key: string,
599+
value: unknown,
600+
sdkName: string,
601+
): boolean {
602+
const lower = key.toLowerCase();
603+
if (
604+
isSdkAttribute(key) ||
605+
SDK_LOG_ATTRIBUTE_KEYS.has(lower) ||
606+
lower.startsWith("logger.")
607+
) {
608+
return true;
609+
}
610+
if (lower === "request") {
611+
return (
612+
sdkName.startsWith("sentry.python") ||
613+
(typeof value === "string" && REQUEST_REPR_RE.test(value))
614+
);
615+
}
616+
return SDK_LOG_ATTRIBUTE_KEYS_BY_SDK.some(
617+
([sdk, keys]) => sdkName.startsWith(sdk) && keys.has(lower),
566618
);
567619
}
568620

@@ -681,6 +733,27 @@ function logAttributeEntries(logEntry: LogEntry): [string, unknown][] {
681733
.map(([k, v]) => [k, v.value]);
682734
}
683735

736+
/**
737+
* Split a log's attributes into the app's own and the SDK's, by
738+
* {@link isSdkLogAttribute}. The SDK name comes from the log's
739+
* `sentry.sdk.name`, else the envelope header.
740+
*/
741+
function splitLogAttributes(
742+
logEntry: LogEntry,
743+
header: Record<string, unknown>,
744+
): { custom: [string, unknown][]; sdk: [string, unknown][] } {
745+
const fromLog = logEntry.attributes?.["sentry.sdk.name"]?.value;
746+
const fromHeader = (header["sdk"] as { name?: unknown } | undefined)?.name;
747+
const name = fromLog ?? fromHeader;
748+
const sdkName = typeof name === "string" ? name : "";
749+
const custom: [string, unknown][] = [];
750+
const sdk: [string, unknown][] = [];
751+
for (const entry of logAttributeEntries(logEntry)) {
752+
(isSdkLogAttribute(entry[0], entry[1], sdkName) ? sdk : custom).push(entry);
753+
}
754+
return { custom, sdk };
755+
}
756+
684757
/**
685758
* Extract the trace ID from a log entry's attributes.
686759
*
@@ -701,18 +774,20 @@ function extractLogTraceId(logEntry: LogEntry): string | undefined {
701774
*
702775
* User-supplied attributes are rendered alphabetically by key so repeated log
703776
* lines align column-for-column and are easy to scan. SDK-default attributes
704-
* (`sentry.*`, `code.*`, `logger.*`, `user.*`, … see
705-
* {@link SDK_ATTRIBUTE_PREFIXES} and {@link SDK_ATTRIBUTE_KEYS}) are omitted
706-
* from the inline list; the trace ID is surfaced as a compact `[trace:…]`
707-
* token instead.
777+
* (`sentry.*`, `code.*`, `logger.*`, the scope user, … see
778+
* {@link isSdkLogAttribute}) are omitted from the inline list; the trace ID
779+
* is surfaced as a compact `[trace:…]` token instead.
708780
*/
709-
export function formatSingleLog(logEntry: LogEntry, source: string): string {
781+
export function formatSingleLog(
782+
logEntry: LogEntry,
783+
source: string,
784+
header: Record<string, unknown> = {},
785+
): string {
710786
const level = logEntry.level ?? "log";
711787
let msg = sanitize(logEntry.body ?? "");
712788

713-
const attrs = logAttributeEntries(logEntry)
714-
.filter(([k]) => !isSdkAttribute(k))
715-
.sort(([a], [b]) => a.localeCompare(b))
789+
const attrs = splitLogAttributes(logEntry, header)
790+
.custom.sort(([a], [b]) => a.localeCompare(b))
716791
.map(([k, v]) => muted(`[${sanitize(k)}=${sanitize(String(v))}]`));
717792
if (attrs.length > 0) {
718793
msg += ` ${attrs.join(" ")}`;
@@ -749,13 +824,11 @@ export function formatLogItem(
749824
// One log batch comes from one SDK client, so any browser log places all.
750825
const source = inferSource(header, undefined, items.map(logAttributes));
751826
return items.flatMap((logEntry) => {
752-
const line = formatSingleLog(logEntry, source);
827+
const line = formatSingleLog(logEntry, source, header);
753828
if (!showAttributes) {
754829
return [line];
755830
}
756-
const sdk = logAttributeEntries(logEntry).filter(([k]) =>
757-
isSdkAttribute(k),
758-
);
831+
const { sdk } = splitLogAttributes(logEntry, header);
759832
return [line, ...formatAttrGroup("sdk attributes", sdk)];
760833
});
761834
}
@@ -1297,20 +1370,7 @@ function formatLogJson(
12971370
level: entry.level ?? "log",
12981371
message: stripBidi(entry.body ?? ""),
12991372
attributes: entry.attributes
1300-
? Object.fromEntries(
1301-
Object.entries(entry.attributes)
1302-
.filter(
1303-
([k, v]) =>
1304-
isUserLogAttribute(k) &&
1305-
(includeAttributes || !isSdkAttribute(k)) &&
1306-
v.value !== null &&
1307-
v.value !== undefined,
1308-
)
1309-
.map(([k, v]) => [
1310-
stripBidi(k),
1311-
typeof v.value === "string" ? stripBidi(v.value) : v.value,
1312-
]),
1313-
)
1373+
? jsonLogAttributes(entry, header, includeAttributes)
13141374
: undefined,
13151375
source,
13161376
},
@@ -1320,6 +1380,22 @@ function formatLogJson(
13201380
);
13211381
}
13221382

1383+
/**
1384+
* A log's attributes for its JSON record: the custom ones, plus the SDK ones
1385+
* (except `sentry.*`) when `includeAttributes` is true.
1386+
*/
1387+
function jsonLogAttributes(
1388+
entry: LogEntry,
1389+
header: Record<string, unknown>,
1390+
includeAttributes: boolean,
1391+
): Record<string, unknown> {
1392+
const { custom, sdk } = splitLogAttributes(entry, header);
1393+
const entries = includeAttributes
1394+
? [...custom, ...sdk.filter(([k]) => isUserLogAttribute(k))]
1395+
: custom;
1396+
return Object.fromEntries(entries);
1397+
}
1398+
13231399
/** Format a standalone span item as JSON objects (one per span). */
13241400
function formatSpanJson(
13251401
payload: Record<string, unknown>,

‎packages/cli/test/commands/local/event-summary.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,17 @@ describe("summarizeEnvelope", () => {
173173
});
174174
});
175175

176+
test("ranks warn and warning logs the same", () => {
177+
expect(
178+
summarize("log", {
179+
items: [
180+
{ level: "warn", body: "Retrying", timestamp: 1_794_947_106 },
181+
{ level: "warning", body: "Disk low", timestamp: 1_794_947_107 },
182+
],
183+
}).title,
184+
).toBe("Retrying");
185+
});
186+
176187
test("titles session aggregates like the viewer", () => {
177188
expect(
178189
summarize("sessions", {

0 commit comments

Comments
 (0)