: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): severity level column and sampling guidance for patterns (#68258)
Jon McCallum65f3d26b77c1
diff --git a/products/logs/backend/log_patterns.py b/products/logs/backend/log_patterns.pyindex 8c992994cf9f..d612c59d056d 100644--- a/products/logs/backend/log_patterns.py+++ b/products/logs/backend/log_patterns.py@@ -58,6 +58,8 @@ class MinedPattern:services: list[str]# Raw sample counts per caller-supplied time bucket (empty when no buckets given).bucket_counts: list[int]+ # Raw sample counts keyed by lowercased severity_text.+ severity_counts: dict[str, int]@dataclass@@ -66,10 +68,10 @@ class _Accumulator:first_seen: dt.datetimelast_seen: dt.datetimecount: int = 0- error_count: int = 0examples: list[str] = 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)def _prepare_body(body: str, truncate: int) -> str:@@ -157,8 +159,8 @@ def mine_patterns(acc.last_seen = sample.timestampacc.count += 1- if sample.severity_text.lower() in _ERROR_SEVERITIES:- acc.error_count += 1+ severity = sample.severity_text.lower()+ acc.severity_counts[severity] = acc.severity_counts.get(severity, 0) + 1if len(acc.examples) < max_examples and prepared not in acc.examples:acc.examples.append(prepared)if sample.service_name not in acc.services and len(acc.services) < max_services:@@ -174,12 +176,13 @@ def mine_patterns(pattern=acc.template,count=acc.count,volume_share_pct=round(acc.count / total * 100, 2),- error_count=acc.error_count,+ error_count=sum(acc.severity_counts.get(s, 0) for s in _ERROR_SEVERITIES),first_seen=acc.first_seen,last_seen=acc.last_seen,examples=acc.examples,services=acc.services,bucket_counts=acc.bucket_counts,+ severity_counts=acc.severity_counts,)for acc in accumulators.values()]diff --git a/products/logs/backend/patterns_query_runner.py b/products/logs/backend/patterns_query_runner.pyindex b3b5e42b0cb3..f31359f60c7e 100644--- a/products/logs/backend/patterns_query_runner.py+++ b/products/logs/backend/patterns_query_runner.py@@ -292,4 +292,7 @@ def _serialize(pattern: MinedPattern, *, total_count: int, scanned_count: int) -"examples": 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,+ # so extrapolating the map would add payload without changing what it says.+ "severity_counts": pattern.severity_counts,}diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.pyindex 671bb7a9e112..39063f1da197 100644--- a/products/logs/backend/presentation/views/api.py+++ b/products/logs/backend/presentation/views/api.py@@ -710,6 +710,13 @@ class _LogPatternSerializer(serializers.Serializer):"the volume shape over the window, not exact per-bucket tallies."),)+ severity_counts = serializers.DictField(+ child=serializers.IntegerField(),+ help_text=(+ '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."+ ),+ )class _LogsPatternsSparklineBucketSerializer(serializers.Serializer):diff --git a/products/logs/backend/test/test_patterns_query_runner.py b/products/logs/backend/test/test_patterns_query_runner.pyindex e6879643ed2d..0676aec9745e 100644--- a/products/logs/backend/test/test_patterns_query_runner.py+++ b/products/logs/backend/test/test_patterns_query_runner.py@@ -67,6 +67,7 @@ class TestPatternsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert by_template["User <*> not found"]["estimated_count"] == 3assert by_template["User <*> not found"]["error_count"] == 3assert by_template["User <*> not found"]["estimated_error_count"] == 3+ assert by_template["User <*> not found"]["severity_counts"] == {"error": 3}assert by_template["User <*> not found"]["services"] == ["auth"]# Unsliced windows bucket uniformly; every sampled occurrence lands in some bucket.assert len(results["sparkline_buckets"]) == 24diff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsxindex b4a95a470da7..94b829250d83 100644--- a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx@@ -7,10 +7,65 @@ import { Sparkline } from 'lib/components/Sparkline'import { TZLabel } from 'lib/components/TZLabel'import { humanFriendlyLargeNumber, humanFriendlyNumber } from 'lib/utils/numbers'+import 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 { logsPatternsLogic } from './logsPatternsLogic'+// Most-severe-first, so ties in sample counts resolve to the stronger signal.+const SEVERITY_RANK: LogMessage['severity_text'][] = ['fatal', 'error', 'warn', 'info', 'debug', 'trace']++// Non-canonical spellings services emit (Python's default "warning", syslog's "err"/"crit", …),+// folded onto the OTel-canonical level so their counts aren't silently dropped from the Level column.+const SEVERITY_ALIASES: Record<string, LogMessage['severity_text']> = {+ warning: 'warn',+ err: 'error',+ critical: 'fatal',+ crit: 'fatal',+ alert: 'fatal',+ emerg: 'fatal',+ emergency: 'fatal',+ panic: 'fatal',+ notice: 'info',+ verbose: 'trace',+}++function canonicalSeverity(raw: string): LogMessage['severity_text'] | null {+ if ((SEVERITY_RANK as string[]).includes(raw)) {+ return raw as LogMessage['severity_text']+ }+ return SEVERITY_ALIASES[raw] ?? null+}++// Dominant severity by sample count. Non-canonical spellings are folded onto their canonical+// level; genuinely unknown levels keep their raw key so they still surface (rather than showing+// "-"). Ties break toward the more severe level.+function dominantSeverity(severityCounts: Record<string, number>): string | null {+ const folded: Record<string, number> = {}+ for (const [raw, count] of Object.entries(severityCounts)) {+ if (count <= 0) {+ continue+ }+ const key = canonicalSeverity(raw) ?? raw+ folded[key] = (folded[key] ?? 0) + count+ }+ let best: string | null = null+ let bestCount = 0+ let bestRank = SEVERITY_RANK.length+ for (const [key, count] of Object.entries(folded)) {+ const canonical = canonicalSeverity(key)+ const rank = canonical ? SEVERITY_RANK.indexOf(canonical) : SEVERITY_RANK.length+ if (count > bestCount || (count === bestCount && rank < bestRank)) {+ best = key+ bestCount = count+ bestRank = rank+ }+ }+ return best+}+// 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.@@ -55,6 +110,19 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {}const columns: LemonTableColumns<_LogPatternApi> = [+ {+ title: 'Level',+ key: 'severity',+ width: 0,+ render: (_, row) => {+ const severity = dominantSeverity(row.severity_counts)+ if (!severity) {+ return <span className="text-muted">-</span>+ }+ const canonical = canonicalSeverity(severity)+ return canonical ? <LogTag level={canonical} /> : <LemonTag>{severity}</LemonTag>+ },+ },{title: 'Pattern',dataIndex: 'pattern',@@ -132,7 +200,8 @@ export function LogsPatterns({ id }: { id: string }): JSX.Element {1)}% of the window`: ''}- . Counts are estimates for the full window — hover a count for the underlying sample figure.+ . Counts are estimates for the full window — hover a count for the underlying sample figure. Narrow+ your filters (a service, a severity, or a shorter time range) to sharpen the sample.</LemonBanner>)}<LemonTablediff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.tsindex d99242633e75..86e8e067e80c 100644--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts@@ -32,6 +32,7 @@ const RESPONSE: _LogsPatternsResponseApi = {examples: [],services: ['auth'],sparkline: [1, 2],+ severity_counts: { error: 3 },},],scanned_count: 3,diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.tsindex 5e45f9397a12..dab9475f6845 100644--- a/products/logs/frontend/generated/api.schemas.ts+++ b/products/logs/frontend/generated/api.schemas.ts@@ -1070,6 +1070,11 @@ export interface _LogsPatternsRequestApi {query: _LogsPatternsBodyApi}+/**+ * 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.+ */+export type _LogPatternApiSeverityCounts = { [key: string]: number }+export interface _LogPatternApi {/** 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@@ -1093,6 +1098,8 @@ export interface _LogPatternApi {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. */sparkline: number[]+ /** 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. */+ severity_counts: _LogPatternApiSeverityCounts}export interface _LogsPatternsSparklineBucketApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 65703e3bdd96..4a0db4356b28 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -54521,6 +54521,11 @@ export namespace Schemas {count: number;}+ /**+ * 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.+ */+ export type _LogPatternSeverityCounts = {[key: string]: number};+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;@@ -54544,6 +54549,8 @@ export namespace Schemas {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. */sparkline: number[];+ /** 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. */+ severity_counts: _LogPatternSeverityCounts;}/**