Skip to content

: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.

feat(logs): add /logs/patterns endpoint and generated types (#66293)

Jon McCallum302dada8c913
diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.py
index eda2b6dbb1c1..72f0f044b14c 100644
--- a/products/logs/backend/presentation/views/api.py
+++ b/products/logs/backend/presentation/views/api.py
@@ -48,6 +48,7 @@ from products.logs.backend.log_attributes_query_runner import LogAttributesQuery
from products.logs.backend.log_facet_values_query_runner import FACET_FIELDS, LogFacetValuesQueryRunner
from products.logs.backend.log_values_query_runner import LogValuesQueryRunner
from products.logs.backend.logs_query_runner import CachedLogsQueryResponse, LogsQueryResponse, LogsQueryRunner
+from products.logs.backend.patterns_query_runner import PatternsQueryRunner
from products.logs.backend.presentation.views.alerts_api import LogsAlertViewSet
from products.logs.backend.presentation.views.explain import LogExplainViewSet
from products.logs.backend.presentation.views.sampling_api import LogsSamplingRuleViewSet
@@ -628,6 +629,91 @@ class _LogsServicesResponseSerializer(serializers.Serializer):
)
+class _LogsPatternsBodySerializer(serializers.Serializer):
+ dateRange = _DateRangeSerializer(
+ required=False,
+ help_text="Date range to mine patterns from. Defaults to last hour.",
+ )
+ severityLevels = serializers.ListField(
+ child=serializers.ChoiceField(choices=["trace", "debug", "info", "warn", "error", "fatal"]),
+ required=False,
+ default=list,
+ help_text="Filter by log severity levels before mining.",
+ )
+ serviceNames = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ default=list,
+ help_text="Restrict mining to these service names.",
+ )
+ searchTerm = serializers.CharField(
+ required=False, help_text="Full-text search term to filter log bodies before mining."
+ )
+ filterGroup = serializers.ListField(
+ child=_LogPropertyFilterSerializer(),
+ required=False,
+ default=list,
+ help_text="Property filters applied before mining. Same shape as the query-logs endpoint.",
+ )
+
+
+class _LogsPatternsRequestSerializer(serializers.Serializer):
+ query = _LogsPatternsBodySerializer(help_text="The patterns query to execute.")
+
+
+class _LogPatternSerializer(serializers.Serializer):
+ pattern = serializers.CharField(
+ help_text=(
+ '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."
+ ),
+ )
+ count = serializers.IntegerField(
+ help_text=(
+ "Occurrences of this pattern within the sample. When `sampled` is true this is a sample "
+ "count, not the full-window total — scale by `total_count / scanned_count` to estimate."
+ ),
+ )
+ volume_share_pct = serializers.FloatField(
+ help_text="Share of the sampled log volume this pattern represents (0–100).",
+ )
+ error_count = serializers.IntegerField(
+ help_text='Sampled occurrences at severity "error" or "fatal".',
+ )
+ 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.",
+ )
+ services = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Up to 4 distinct service names this pattern was observed in.",
+ )
+
+
+class _LogsPatternsResponseSerializer(serializers.Serializer):
+ patterns = _LogPatternSerializer(
+ many=True,
+ help_text="Mined patterns ordered by `count` descending.",
+ )
+ scanned_count = serializers.IntegerField(
+ help_text="Number of log rows fed to the miner (the sample size, capped at the sample limit).",
+ )
+ total_count = serializers.IntegerField(
+ help_text=(
+ "Total log rows matching the filters in the window, before sampling. Use with "
+ "`scanned_count` to scale per-pattern counts when `sampled` is true."
+ ),
+ )
+ sampled = serializers.BooleanField(
+ help_text=(
+ "True when the window held more rows than the sample cap, so patterns were mined from "
+ "an evenly-distributed random sample rather than every matching row."
+ ),
+ )
+
+
class _LogAttributeEntrySerializer(serializers.Serializer):
name = serializers.CharField()
propertyFilterType = serializers.CharField(
@@ -1004,6 +1090,45 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
return Response(response.results, status=status.HTTP_200_OK)
+ @extend_schema(request=_LogsPatternsRequestSerializer, responses={200: _LogsPatternsResponseSerializer})
+ @action(detail=False, methods=["POST"], required_scopes=["logs:read"])
+ def patterns(self, request: Request, *args, **kwargs) -> Response:
+ tag_queries(product=Product.LOGS, feature=Feature.QUERY)
+ query_data = request.data.get("query", {})
+
+ query = LogsQuery(
+ dateRange=self.get_model(query_data.get("dateRange"), DateRange),
+ severityLevels=query_data.get("severityLevels", []),
+ serviceNames=query_data.get("serviceNames", []),
+ searchTerm=query_data.get("searchTerm", None),
+ filterGroup=self._normalize_filter_group(query_data.get("filterGroup", None)),
+ )
+
+ runner = PatternsQueryRunner(team=self.team, query=query)
+ response = runner.run(
+ ExecutionMode.CALCULATE_BLOCKING_ALWAYS,
+ analytics_props=get_request_analytics_properties(request),
+ )
+ assert isinstance(response, LogsQueryResponse | CachedLogsQueryResponse)
+
+ report_user_action(
+ request.user,
+ "logs patterns queried",
+ {
+ "patterns_count": len(response.results.get("patterns", []))
+ if isinstance(response.results, dict)
+ else 0,
+ "sampled": response.results.get("sampled") if isinstance(response.results, dict) else None,
+ "has_search_term": bool(query_data.get("searchTerm")),
+ "severity_levels_count": len(query_data.get("severityLevels", [])),
+ "service_names_count": len(query_data.get("serviceNames", [])),
+ },
+ team=self.team,
+ request=request,
+ )
+
+ return Response(response.results, status=status.HTTP_200_OK)
+
@extend_schema(parameters=[_LogsAttributesQuerySerializer], responses={200: _LogsAttributesResponseSerializer})
@action(detail=False, methods=["GET"], required_scopes=["logs:read"])
def attributes(self, request: Request, *args, **kwargs) -> Response:
diff --git a/products/logs/backend/test/test_patterns_api.py b/products/logs/backend/test/test_patterns_api.py
new file mode 100644
index 000000000000..6f3936f9ffa3
--- /dev/null
+++ b/products/logs/backend/test/test_patterns_api.py
@@ -0,0 +1,77 @@
+import json
+
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from rest_framework import status
+
+from posthog.clickhouse.client import sync_execute
+
+
+class TestPatternsAPI(ClickhouseTestMixin, APIBaseTest):
+ def _insert(self, rows: list[dict]) -> None:
+ sql = "".join(json.dumps({"team_id": self.team.id, **r}) + "\n" for r in rows)
+ sync_execute(f"INSERT INTO logs FORMAT JSONEachRow\n{sql}")
+
+ def _request(self, query: dict, expected_status: int = status.HTTP_200_OK):
+ response = self.client.post(f"/api/projects/{self.team.id}/logs/patterns", data={"query": query})
+ self.assertEqual(response.status_code, expected_status)
+ return response.json() if expected_status == status.HTTP_200_OK else response
+
+ @freeze_time("2026-06-23T13:00:00Z")
+ def test_patterns_endpoint_returns_mined_patterns(self) -> None:
+ self._insert(
+ [
+ {
+ "timestamp": "2026-06-23 12:00:00.000000",
+ "body": f"User {name} not found",
+ "severity_text": "error",
+ "service_name": "auth",
+ }
+ for name in ("alice", "bob", "carol")
+ ]
+ )
+
+ body = self._request(
+ {
+ "dateRange": {"date_from": "2026-06-23T00:00:00Z", "date_to": "2026-06-23T13:00:00Z"},
+ "filterGroup": {"type": "AND", "values": [{"type": "AND", "values": []}]},
+ }
+ )
+
+ assert body["scanned_count"] == 3
+ assert body["total_count"] == 3
+ assert body["sampled"] is False
+ pattern = next(p for p in body["patterns"] if p["pattern"] == "User <*> not found")
+ assert pattern["count"] == 3
+ assert pattern["error_count"] == 3
+ assert pattern["services"] == ["auth"]
+
+ @freeze_time("2026-06-23T13:00:00Z")
+ def test_patterns_endpoint_accepts_flat_filter_group(self) -> None:
+ self._insert(
+ [
+ {
+ "timestamp": "2026-06-23 12:00:00.000000",
+ "body": "db connection failed",
+ "severity_text": "error",
+ "service_name": "api",
+ },
+ {
+ "timestamp": "2026-06-23 12:01:00.000000",
+ "body": "cache warmed",
+ "severity_text": "info",
+ "service_name": "api",
+ },
+ ]
+ )
+
+ body = self._request(
+ {
+ "dateRange": {"date_from": "2026-06-23T00:00:00Z", "date_to": "2026-06-23T13:00:00Z"},
+ "filterGroup": [{"key": "message", "type": "log", "operator": "icontains", "value": "connection"}],
+ }
+ )
+
+ assert body["scanned_count"] == 1
+ assert body["total_count"] == 1
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index d144816a2f42..411bc0e8a764 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1042,6 +1042,54 @@ export interface _LogsFacetValuesResponseApi {
results: _LogFacetValueApi[]
}
+export interface _LogsPatternsBodyApi {
+ /** Date range to mine patterns from. Defaults to last hour. */
+ dateRange?: _DateRangeApi
+ /** Filter by log severity levels before mining. */
+ severityLevels?: SeverityLevelsEnumApi[]
+ /** Restrict mining to these service names. */
+ serviceNames?: string[]
+ /** Full-text search term to filter log bodies before mining. */
+ searchTerm?: string
+ /** Property filters applied before mining. Same shape as the query-logs endpoint. */
+ filterGroup?: _LogPropertyFilterApi[]
+}
+
+export interface _LogsPatternsRequestApi {
+ /** The patterns query to execute. */
+ query: _LogsPatternsBodyApi
+}
+
+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
+ /** Occurrences of this pattern within the sample. When `sampled` is true this is a sample count, not the full-window total — scale by `total_count / scanned_count` to estimate. */
+ count: number
+ /** Share of the sampled log volume this pattern represents (0–100). */
+ volume_share_pct: number
+ /** Sampled occurrences at severity "error" or "fatal". */
+ error_count: number
+ /** ISO 8601 timestamp of the earliest sampled occurrence. */
+ 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 4 distinct service names this pattern was observed in. */
+ services: string[]
+}
+
+export interface _LogsPatternsResponseApi {
+ /** Mined patterns ordered by `count` descending. */
+ patterns: _LogPatternApi[]
+ /** Number of log rows fed to the miner (the sample size, capped at the sample limit). */
+ scanned_count: number
+ /** Total log rows matching the filters in the window, before sampling. Use with `scanned_count` to scale per-pattern counts when `sampled` is true. */
+ total_count: number
+ /** True when the window held more rows than the sample cap, so patterns were mined from an evenly-distributed random sample rather than every matching row. */
+ sampled: boolean
+}
+
/**
* * `latest` - latest
* * `earliest` - earliest
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index 868562f8823d..0f9ac43035c6 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -43,6 +43,8 @@ import type {
_LogsCountResponseApi,
_LogsFacetValuesRequestApi,
_LogsFacetValuesResponseApi,
+ _LogsPatternsRequestApi,
+ _LogsPatternsResponseApi,
_LogsQueryRequestApi,
_LogsQueryResponseApi,
_LogsServicesRequestApi,
@@ -411,6 +413,23 @@ export const logsHasLogsRetrieve = async (
})
}
+export const getLogsPatternsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/logs/patterns/`
+}
+
+export const logsPatternsCreate = async (
+ projectId: string,
+ _logsPatternsRequestApi: _LogsPatternsRequestApi,
+ options?: RequestInit
+): Promise<_LogsPatternsResponseApi> => {
+ return apiMutator<_LogsPatternsResponseApi>(getLogsPatternsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(_logsPatternsRequestApi),
+ })
+}
+
export const getLogsQueryCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/logs/query/`
}
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index c616c5b7ae5d..f204227938f2 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -709,6 +709,88 @@ export const LogsFacetValuesCreateBody = /* @__PURE__ */ zod.object({
.describe('The facet values query to execute.'),
})
+export const LogsPatternsCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .object({
+ dateRange: zod
+ .object({
+ date_from: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Start of the date range. Accepts ISO 8601 timestamps or relative formats: -7d, -1h, -1mStart, etc.'
+ ),
+ date_to: zod
+ .string()
+ .nullish()
+ .describe('End of the date range. Same format as date_from. Omit or null for \"now\".'),
+ })
+ .optional()
+ .describe('Date range to mine patterns from. Defaults to last hour.'),
+ severityLevels: zod
+ .array(
+ zod
+ .enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal'])
+ .describe(
+ '\* `trace` - trace\n\* `debug` - debug\n\* `info` - info\n\* `warn` - warn\n\* `error` - error\n\* `fatal` - fatal'
+ )
+ )
+ .optional()
+ .describe('Filter by log severity levels before mining.'),
+ serviceNames: zod.array(zod.string()).optional().describe('Restrict mining to these service names.'),
+ searchTerm: zod.string().optional().describe('Full-text search term to filter log bodies before mining.'),
+ filterGroup: zod
+ .array(
+ zod.object({
+ key: zod
+ .string()
+ .describe(
+ 'Attribute key. For type \"log\", use \"message\". For \"log_attribute\"\/\"log_resource_attribute\", use the attribute key (e.g. \"k8s.container.name\").'
+ ),
+ type: zod
+ .enum(['log', 'log_attribute', 'log_resource_attribute'])
+ .describe(
+ '\* `log` - log\n\* `log_attribute` - log_attribute\n\* `log_resource_attribute` - log_resource_attribute'
+ )
+ .describe(
+ '\"log\" filters the log body\/message. \"log_attribute\" filters log-level attributes. \"log_resource_attribute\" filters resource-level attributes.\n\n\* `log` - log\n\* `log_attribute` - log_attribute\n\* `log_resource_attribute` - log_resource_attribute'
+ ),
+ operator: zod
+ .enum([
+ 'exact',
+ 'is_not',
+ 'icontains',
+ 'not_icontains',
+ 'regex',
+ 'not_regex',
+ 'gt',
+ 'lt',
+ 'is_date_exact',
+ 'is_date_before',
+ 'is_date_after',
+ 'is_set',
+ 'is_not_set',
+ ])
+ .describe(
+ '\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_date_exact` - is_date_exact\n\* `is_date_before` - is_date_before\n\* `is_date_after` - is_date_after\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'
+ )
+ .describe(
+ 'Comparison operator.\n\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `lt` - lt\n\* `is_date_exact` - is_date_exact\n\* `is_date_before` - is_date_before\n\* `is_date_after` - is_date_after\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'
+ ),
+ value: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Value to compare against. String, number, or array of strings. Omit for is_set\/is_not_set operators.'
+ ),
+ })
+ )
+ .optional()
+ .describe('Property filters applied before mining. Same shape as the query-logs endpoint.'),
+ })
+ .describe('The patterns query to execute.'),
+})
+
export const logsQueryCreateBodyQueryOneSeverityLevelsDefault = []
export const logsQueryCreateBodyQueryOneServiceNamesDefault = []
export const logsQueryCreateBodyQueryOneFilterGroupDefault = []
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index 629b1f964abf..36025545584d 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -347,6 +347,9 @@ tools:
logs-has-logs-retrieve:
operation: logs_has_logs_retrieve
enabled: false
+ logs-patterns-create:
+ operation: logs_patterns_create
+ enabled: false
logs-sampling-rules-create:
operation: logs_sampling_rules_create
enabled: false
diff --git a/pyproject.toml b/pyproject.toml
index 53861d8e51f3..ea566a12f268 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -549,6 +549,7 @@ ignore_imports = [
"products.logs.backend.presentation.views.api -> products.logs.backend.log_facet_values_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.log_values_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.logs_query_runner",
+ "products.logs.backend.presentation.views.api -> products.logs.backend.patterns_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.services_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.sparkline_query_runner",
"products.logs.backend.presentation.views.alerts_api -> products.logs.backend.alert_check_query",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 394a79482d13..c5c9596e38e2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -53010,6 +53010,25 @@ export namespace Schemas {
count: 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;
+ /** Occurrences of this pattern within the sample. When `sampled` is true this is a sample count, not the full-window total — scale by `total_count / scanned_count` to estimate. */
+ count: number;
+ /** Share of the sampled log volume this pattern represents (0–100). */
+ volume_share_pct: number;
+ /** Sampled occurrences at severity "error" or "fatal". */
+ error_count: number;
+ /** ISO 8601 timestamp of the earliest sampled occurrence. */
+ 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 4 distinct service names this pattern was observed in. */
+ services: string[];
+ }
+
/**
* * `log` - log
* * `log_attribute` - log_attribute
@@ -53192,6 +53211,35 @@ export namespace Schemas {
results: _LogFacetValue[];
}
+ export interface _LogsPatternsBody {
+ /** Date range to mine patterns from. Defaults to last hour. */
+ dateRange?: _DateRange;
+ /** Filter by log severity levels before mining. */
+ severityLevels?: SeverityLevelsEnum[];
+ /** Restrict mining to these service names. */
+ serviceNames?: string[];
+ /** Full-text search term to filter log bodies before mining. */
+ searchTerm?: string;
+ /** Property filters applied before mining. Same shape as the query-logs endpoint. */
+ filterGroup?: _LogPropertyFilter[];
+ }
+
+ export interface _LogsPatternsRequest {
+ /** The patterns query to execute. */
+ query: _LogsPatternsBody;
+ }
+
+ export interface _LogsPatternsResponse {
+ /** Mined patterns ordered by `count` descending. */
+ patterns: _LogPattern[];
+ /** Number of log rows fed to the miner (the sample size, capped at the sample limit). */
+ scanned_count: number;
+ /** Total log rows matching the filters in the window, before sampling. Use with `scanned_count` to scale per-pattern counts when `sampled` is true. */
+ total_count: number;
+ /** True when the window held more rows than the sample cap, so patterns were mined from an evenly-distributed random sample rather than every matching row. */
+ sampled: boolean;
+ }
+
export interface _LogsQueryBody {
/** Date range for the query. Defaults to last hour. */
dateRange?: _DateRange;