Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/cli-docs/src/fragments/commands/local.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Start the local dev server and tail events
- `-q, --quiet - Suppress per-envelope tail output`
- `-f, --filter <value>... - Only show items of this type (repeatable: error, transaction, log, ai)`
- `-F, --format <value> - 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 <value> - Maximum envelopes retained by this receiver or session`
- `--session <value> - Create a daemon-owned telemetry session with this label`
Expand Down Expand Up @@ -195,7 +195,7 @@ Run a command with the local dev server enabled
- `-V, --verify - Verify SDK sends events, then exit`
- `-t, --timeout <value> - Kill the child after N seconds (0 = no timeout; defaults to 30 s in --verify mode) - (default: "0")`
- `-F, --format <value> - 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 <value> - Maximum envelopes retained by this receiver or session`
- `--session <value> - Create a daemon-owned telemetry session with this label`
Expand Down
25 changes: 11 additions & 14 deletions packages/cli/src/commands/local/event-summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value)
Expand Down Expand Up @@ -109,11 +101,16 @@ function logTraceId(log: Record<string, unknown>): 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. */
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/local/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/local/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
146 changes: 111 additions & 35 deletions packages/cli/src/lib/formatters/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>][] =
[
["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 = " ";
Expand All @@ -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),
);
}

Expand Down Expand Up @@ -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<string, unknown>,
): { 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.
*
Expand All @@ -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, unknown> = {},
): 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(" ")}`;
Expand Down Expand Up @@ -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)];
});
}
Expand Down Expand Up @@ -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,
},
Expand All @@ -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<string, unknown>,
includeAttributes: boolean,
): Record<string, unknown> {
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<string, unknown>,
Expand Down
11 changes: 11 additions & 0 deletions packages/cli/test/commands/local/event-summary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", {
Expand Down
Loading
Loading