:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(logs): expandable pattern rows with structured example logs (#68263)
Jon McCallumddc5ea2b2dfc
diff --git a/products/logs/backend/log_patterns.py b/products/logs/backend/log_patterns.pyindex d612c59d056d..3720c277c16c 100644--- a/products/logs/backend/log_patterns.py+++ b/products/logs/backend/log_patterns.py@@ -54,7 +54,9 @@ class MinedPattern:error_count: intfirst_seen: dt.datetimelast_seen: dt.datetime- examples: list[str]+ # Sampled rows that produced this pattern; `body` is the prepared (whitespace-collapsed,+ # truncated) form the miner saw, not the raw log line.+ examples: list[LogSample]services: list[str]# Raw sample counts per caller-supplied time bucket (empty when no buckets given).bucket_counts: list[int]@@ -68,7 +70,7 @@ class _Accumulator:first_seen: dt.datetimelast_seen: dt.datetimecount: int = 0- examples: list[str] = field(default_factory=list)+ examples: list[LogSample] = field(default_factory=list)services: list[str] = field(default_factory=list)bucket_counts: list[int] = field(default_factory=list)severity_counts: dict[str, int] = field(default_factory=dict)@@ -126,7 +128,7 @@ def mine_patterns(return []max_patterns = max_patterns if max_patterns is not None else _env("LOGS_PATTERNS_MAX_PATTERNS", 200, int)- max_examples = max_examples if max_examples is not None else _env("LOGS_PATTERNS_MAX_EXAMPLES", 3, int)+ max_examples = max_examples if max_examples is not None else _env("LOGS_PATTERNS_MAX_EXAMPLES", 10, int)max_services = max_services if max_services is not None else _env("LOGS_PATTERNS_MAX_SERVICES", 4, int)truncate = _env("LOGS_PATTERNS_BODY_TRUNCATE", 512, int)sim_th = _env("LOGS_PATTERNS_SIM_TH", 0.4, float)@@ -161,8 +163,15 @@ def mine_patterns(acc.count += 1severity = sample.severity_text.lower()acc.severity_counts[severity] = acc.severity_counts.get(severity, 0) + 1- if len(acc.examples) < max_examples and prepared not in acc.examples:- acc.examples.append(prepared)+ if len(acc.examples) < max_examples and all(e.body != prepared for e in acc.examples):+ acc.examples.append(+ LogSample(+ body=prepared,+ severity_text=sample.severity_text,+ service_name=sample.service_name,+ timestamp=sample.timestamp,+ )+ )if sample.service_name not in acc.services and len(acc.services) < max_services:acc.services.append(sample.service_name)if buckets:diff --git a/products/logs/backend/patterns_query_runner.py b/products/logs/backend/patterns_query_runner.pyindex f31359f60c7e..017b4a9d08e8 100644--- a/products/logs/backend/patterns_query_runner.py+++ b/products/logs/backend/patterns_query_runner.py@@ -289,7 +289,15 @@ def _serialize(pattern: MinedPattern, *, total_count: int, scanned_count: int) -"estimated_error_count": estimate(pattern.error_count),"first_seen": pattern.first_seen.isoformat(),"last_seen": pattern.last_seen.isoformat(),- "examples": pattern.examples,+ "examples": [+ {+ "body": example.body,+ "severity_text": example.severity_text,+ "service_name": example.service_name,+ "timestamp": example.timestamp.isoformat(),+ }+ for example in pattern.examples+ ],"services": pattern.services,"sparkline": [estimate(c) for c in pattern.bucket_counts],# Raw sample counts: severity dominance is a proportion, which is scale-invariant,diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex 39063f1da197..f85d703b3d28 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -661,6 +661,18 @@ class _LogsPatternsRequestSerializer(serializers.Serializer):query = _LogsPatternsBodySerializer(help_text="The patterns query to execute.")+class _LogPatternExampleSerializer(serializers.Serializer):+ body = serializers.CharField(+ help_text=(+ "Log body as the miner saw it: whitespace-collapsed and truncated to the mining "+ "length cap, not the raw stored line."+ ),+ )+ severity_text = serializers.CharField(help_text='Severity of the sampled line, e.g. "info", "error".')+ service_name = serializers.CharField(help_text="Service that emitted the sampled line.")+ timestamp = serializers.CharField(help_text="ISO 8601 timestamp of the sampled line.")++class _LogPatternSerializer(serializers.Serializer):pattern = serializers.CharField(help_text=(@@ -694,9 +706,12 @@ class _LogPatternSerializer(serializers.Serializer):)first_seen = serializers.CharField(help_text="ISO 8601 timestamp of the earliest sampled occurrence.")last_seen = serializers.CharField(help_text="ISO 8601 timestamp of the latest sampled occurrence.")- examples = serializers.ListField(- child=serializers.CharField(),- help_text="Up to 3 distinct raw log bodies (truncated) that produced this pattern.",+ examples = _LogPatternExampleSerializer(+ many=True,+ help_text=(+ "Up to 10 distinct sampled log lines that produced this pattern, with severity, "+ "service, and timestamp for display."+ ),)services = serializers.ListField(child=serializers.CharField(),diff --git a/products/logs/backend/test/test_log_patterns.py b/products/logs/backend/test/test_log_patterns.pyindex 110cf39b6d8b..237b85a38557 100644--- a/products/logs/backend/test/test_log_patterns.py+++ b/products/logs/backend/test/test_log_patterns.py@@ -102,12 +102,15 @@ class TestMinePatterns(TestCase):# all five cluster together (the number is masked), but only two examples are keptassert patterns[0].count == 5- assert patterns[0].examples == ["error code 0", "error code 1"]+ assert [e.body for e in patterns[0].examples] == ["error code 0", "error code 1"]+ # examples carry the sampled row's metadata for display, not just the body+ assert patterns[0].examples[0].service_name == "api"+ assert patterns[0].examples[0].severity_text == "info"def test_long_bodies_are_truncated_before_mining(self) -> None:patterns = mine_patterns([_sample("x" * 1000)])- assert len(patterns[0].examples[0]) == 512+ assert len(patterns[0].examples[0].body) == 512def test_first_and_last_seen_span_the_cluster(self) -> None:earliest = dt.datetime(2026, 6, 23, 12, 0, 0, tzinfo=dt.UTC)diff --git a/products/logs/backend/test/test_patterns_query_runner.py b/products/logs/backend/test/test_patterns_query_runner.pyindex 0676aec9745e..6043a19717d2 100644--- a/products/logs/backend/test/test_patterns_query_runner.py+++ b/products/logs/backend/test/test_patterns_query_runner.py@@ -69,6 +69,12 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert by_template["User <*> not found"]["estimated_error_count"] == 3assert by_template["User <*> not found"]["severity_counts"] == {"error": 3}assert by_template["User <*> not found"]["services"] == ["auth"]+ # Examples are structured sampled rows, not bare bodies.+ example = by_template["User <*> not found"]["examples"][0]+ assert example["body"] == "User alice not found"+ assert example["severity_text"] == "error"+ assert example["service_name"] == "auth"+ assert example["timestamp"].startswith("2026-06-23T12:00:00")# Unsliced windows bucket uniformly; every sampled occurrence lands in some bucket.assert len(results["sparkline_buckets"]) == 24assert sum(by_template["User <*> not found"]["sparkline"]) == 3diff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsxindex 94b829250d83..5341542a1e92 100644--- a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx@@ -10,7 +10,7 @@ import { humanFriendlyLargeNumber, humanFriendlyNumber } from 'lib/utils/numbersimport type { LogMessage } from '~/queries/schema/schema-general'import { LogTag } from 'products/logs/frontend/components/LogTag'-import type { _LogPatternApi } from 'products/logs/frontend/generated/api.schemas'+import type { _LogPatternApi, _LogPatternExampleApi } from 'products/logs/frontend/generated/api.schemas'import { logsPatternsLogic } from './logsPatternsLogic'@@ -66,6 +66,47 @@ function dominantSeverity(severityCounts: Record<string, number>): string | nullreturn best}+function PatternExampleRow({ example }: { example: _LogPatternExampleApi }): JSX.Element {+ return (+ <div className="flex items-baseline gap-2 py-0.5">+ <span className="shrink-0">+ <TZLabel time={example.timestamp} className="text-muted text-xs whitespace-nowrap" />+ </span>+ <span className="shrink-0">+ <LogTag level={example.severity_text as LogMessage['severity_text']} />+ </span>+ <span className="text-muted text-xs shrink-0">{example.service_name}</span>+ <span className="font-mono text-xs break-all">{example.body}</span>+ </div>+ )+}++function PatternExpandedRow({ row }: { row: _LogPatternApi }): JSX.Element {+ return (+ <div className="px-2 py-2 flex flex-col gap-2" data-attr="logs-pattern-expanded">+ <div>{renderPatternTemplate(row.pattern)}</div>+ <div className="text-muted text-xs">+ First seen <TZLabel time={row.first_seen} /> · last seen <TZLabel time={row.last_seen} />+ {row.services.length ? <> · {row.services.join(', ')}</> : null}+ </div>+ {row.examples.length ? (+ <>+ <div className="border rounded bg-bg-light p-2 flex flex-col divide-y">+ {row.examples.map((example, i) => (+ <PatternExampleRow key={i} example={example} />+ ))}+ </div>+ <div className="text-muted text-xs">+ Examples are sampled lines, shown as mined (whitespace-collapsed and truncated).+ </div>+ </>+ ) : (+ <span className="text-muted text-xs">No examples were retained for this pattern.</span>+ )}+ </div>+ )+}+// Highlight Drain's `<*>` wildcard and the masking placeholders (`<ip>`, `<num>`, `<uuid>`,// `<hex>`, …) the runner emits — see _MASKING_INSTRUCTIONS in// products/logs/backend/log_patterns.py for the authoritative token vocabulary.@@ -208,6 +249,9 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {columns={columns}dataSource={patterns}loading={patternsResponseLoading}+ expandable={{+ expandedRowRender: (row) => <PatternExpandedRow row={row} />,+ }}defaultSorting={{ columnKey: 'estimated_count', order: -1 }}emptyState={patternsErrordiff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 33fe0a6ffd14..8de94f5c62ae 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1071,6 +1071,17 @@ export interface _LogsPatternsRequestApi {query: _LogsPatternsBodyApi}+export interface _LogPatternExampleApi {+ /** Log body as the miner saw it: whitespace-collapsed and truncated to the mining length cap, not the raw stored line. */+ body: string+ /** Severity of the sampled line, e.g. "info", "error". */+ severity_text: string+ /** Service that emitted the sampled line. */+ service_name: string+ /** ISO 8601 timestamp of the sampled line. */+ timestamp: string+}+/*** Sampled occurrences keyed by lowercased severity ("trace" through "fatal"). Raw sample counts, not extrapolated — severity dominance is a proportion, so scaling would not change it.*/@@ -1093,8 +1104,8 @@ export interface _LogPatternApi {first_seen: string/** ISO 8601 timestamp of the latest sampled occurrence. */last_seen: string- /** Up to 3 distinct raw log bodies (truncated) that produced this pattern. */- examples: string[]+ /** Up to 10 distinct sampled log lines that produced this pattern, with severity, service, and timestamp for display. */+ examples: _LogPatternExampleApi[]/** Up to 4 distinct service names this pattern was observed in. */services: string[]/** Estimated occurrences per time bucket, aligned index-for-index with the response's `sparkline_buckets`. Extrapolated from the sample like `estimated_count`, so it shows the volume shape over the window, not exact per-bucket tallies. */diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9d8798b4b1db..0a5f41e41c7a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -55098,6 +55098,17 @@ export namespace Schemas {*/export type _LogPatternSeverityCounts = {[key: string]: number};+ export interface _LogPatternExample {+ /** Log body as the miner saw it: whitespace-collapsed and truncated to the mining length cap, not the raw stored line. */+ body: string;+ /** Severity of the sampled line, e.g. "info", "error". */+ severity_text: string;+ /** Service that emitted the sampled line. */+ service_name: string;+ /** ISO 8601 timestamp of the sampled line. */+ timestamp: string;+ }+export interface _LogPattern {/** Mined log template with variable tokens masked, e.g. "Connected to <ip> in <num>ms". Tokens: <uuid>, <ip>, <hex>, <num>, plus <*> for word positions Drain found to vary. */pattern: string;@@ -55115,8 +55126,8 @@ export namespace Schemas {first_seen: string;/** ISO 8601 timestamp of the latest sampled occurrence. */last_seen: string;- /** Up to 3 distinct raw log bodies (truncated) that produced this pattern. */- examples: string[];+ /** Up to 10 distinct sampled log lines that produced this pattern, with severity, service, and timestamp for display. */+ examples: _LogPatternExample[];/** Up to 4 distinct service names this pattern was observed in. */services: string[];/** Estimated occurrences per time bucket, aligned index-for-index with the response's `sparkline_buckets`. Extrapolated from the sample like `estimated_count`, so it shows the volume shape over the window, not exact per-bucket tallies. */