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): wire custom columns through query runner and endpoint (#67762)

Jon McCallum20d6c7b45214
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 9c59b1de80aa..ab5ca502c422 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -26846,6 +26846,13 @@
"description": "Cursor for fetching the next page of results",
"type": "string"
},
+ "customColumns": {
+ "description": "Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Values come back on each result row keyed by the aliases in `LogsQueryResponse.columns`.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"dateRange": {
"$ref": "#/definitions/DateRange"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 7629df561006..fd5b2f5dea41 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3397,6 +3397,13 @@ export interface LogsQuery extends DataNode<LogsQueryResponse> {
resourceFingerprint?: string
/** Omit the per-log `attributes` and `resource_attributes` maps from results to keep payloads compact */
excludeAttributes?: boolean
+ /**
+ * Custom column expressions evaluated per log row. Each entry is either a source-prefixed
+ * shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar
+ * HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`).
+ * Values come back on each result row keyed by the aliases in `LogsQueryResponse.columns`.
+ */
+ customColumns?: string[]
}
export interface LogsQueryResponse extends AnalyticsQueryResponseBase {
diff --git a/posthog/schema.py b/posthog/schema.py
index bab7e95ed364..2f264360abd0 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -25025,6 +25025,17 @@ class LogsQuery(BaseModel):
extra="forbid",
)
after: str | None = Field(default=None, description="Cursor for fetching the next page of results")
+ customColumns: list[str] | None = Field(
+ default=None,
+ description=(
+ "Custom column expressions evaluated per log row. Each entry is either a"
+ " source-prefixed shorthand (`attributes.<key>`,"
+ " `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL"
+ " expression (`upper(level)`, `coalesce(attributes['a'],"
+ " attributes['b'])`). Values come back on each result row keyed by the"
+ " aliases in `LogsQueryResponse.columns`."
+ ),
+ )
dateRange: DateRange
excludeAttributes: bool | None = Field(
default=None,
diff --git a/products/logs/backend/column_expressions.py b/products/logs/backend/column_expressions.py
index b58335db5202..b6adf356bc6c 100644
--- a/products/logs/backend/column_expressions.py
+++ b/products/logs/backend/column_expressions.py
@@ -48,6 +48,35 @@ def parse_shorthand(text: str) -> ast.Expr | None:
return path_to_expr(source, path)
+# ClickHouse functions that emit more than one row per input row. They have no place in a per-row
+# custom column: a reader could submit e.g. `arrayJoin(range(1000000000))` and force the logs query
+# to expand every matching row into billions, a low-friction availability hit. Matched case-insensitively.
+# Mirrors posthog.hogql.database.schema.util.where_clause_extractor._ROW_MULTIPLYING_FUNCTIONS.
+_ROW_MULTIPLYING_FUNCTIONS = {"arrayjoin"}
+
+# ClickHouse functions whose output size is driven by a (typically constant) size argument rather than by
+# the row's own data — a reader could submit e.g. `range(1000000000)` or `repeat(body, 1000000000)` and make
+# ClickHouse build a huge array/string for every matching row without multiplying rows, a low-friction
+# availability hit that the row-multiplier check above does not cover. They have no legitimate use in a
+# per-row log column, so we reject them outright rather than trying to bound their argument. Matched
+# case-insensitively.
+_VALUE_GENERATING_FUNCTIONS = {
+ "range",
+ "arraywithconstant",
+ "arrayresize",
+ "repeat",
+ "space",
+ "randomstring",
+ "randomstringutf8",
+ "randomprintableascii",
+ "randomfixedstring",
+ "leftpad",
+ "rightpad",
+ "leftpadutf8",
+ "rightpadutf8",
+}
+
+
class _ScalarValidator(TraversingVisitor):
def visit_select_query(self, node: ast.SelectQuery) -> None:
raise ValueError("Custom columns cannot contain subqueries")
@@ -58,14 +87,28 @@ class _ScalarValidator(TraversingVisitor):
def visit_placeholder(self, node: ast.Placeholder) -> None:
raise ValueError("Custom columns cannot contain placeholders")
+ def visit_window_function(self, node: ast.WindowFunction) -> None:
+ # Window functions (e.g. `row_number() over (order by timestamp)`) evaluate over a frame of
+ # rows, not per-row, forcing ClickHouse to process every matching log before the page limit
+ # applies — the same availability risk as aggregations, which we already reject.
+ raise ValueError("Custom columns cannot contain window functions")
+
def visit_call(self, node: ast.Call) -> None:
+ name = node.name.lower()
if find_hogql_aggregation(node.name) is not None:
raise ValueError(f"Custom columns must be per-row: aggregation {node.name!r} is not allowed")
+ if name in _ROW_MULTIPLYING_FUNCTIONS:
+ raise ValueError(f"Custom columns must be per-row: {node.name!r} can multiply rows and is not allowed")
+ if name in _VALUE_GENERATING_FUNCTIONS:
+ raise ValueError(
+ f"Custom columns must be bounded: {node.name!r} can generate arbitrarily large values and is not allowed"
+ )
super().visit_call(node)
def _validate_scalar(expr: ast.Expr) -> None:
- """Reject subqueries, aggregations, and unresolved placeholders anywhere in `expr`.
+ """Reject subqueries, aggregations, row-multiplying and value-generating functions, and unresolved
+ placeholders anywhere in `expr`.
Scalar function calls, field access, arithmetic, conditionals, and constants all
pass. This is an AST check — the expression is never inspected as a string.
diff --git a/products/logs/backend/logs_query_runner.py b/products/logs/backend/logs_query_runner.py
index 63202586ec93..158c88e6fd82 100644
--- a/products/logs/backend/logs_query_runner.py
+++ b/products/logs/backend/logs_query_runner.py
@@ -18,6 +18,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
+from posthog.hogql.errors import ExposedHogQLError, QueryError
from posthog.hogql.parser import parse_expr, parse_order_expr, parse_select
from posthog.hogql.property import get_lowercase_index_hint, operator_is_negative, property_to_expr
@@ -27,10 +28,19 @@ from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, QueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.filters.mixins.utils import cached_property
+from products.logs.backend.column_expressions import canonical_key, column_to_expr
+
if TYPE_CHECKING:
from posthog.models import Team, User
+# Bounds the per-request fan-out of user-supplied HogQL expressions. Per-expression cost is already
+# bounded by the query's max_execution_time / max_memory_usage; this just caps how many run at once.
+# Enforced in the runner so every LogsQuery entry point (interactive query endpoint and the
+# server-side CSV export worker) is bounded, not just the interactive one.
+MAX_CUSTOM_COLUMNS = 50
+
+
LIVE_LOGS_CHECKPOINT_QUERY = parse_select(
"""
SELECT min(partition_checkpoint) FROM (
@@ -528,6 +538,11 @@ class LogsQueryRunnerMixin(QueryRunner):
return self._filter_builder.resource_filter(existing_filters=existing_filters)
+# Number of fixed SELECT columns in to_query; custom columns are appended after these,
+# so _calculate maps result[_FIXED_COLUMN_COUNT:] onto the custom column aliases.
+_FIXED_COLUMN_COUNT = 15
+
+
class LogsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMixin):
query: LogsQuery
cached_response: CachedLogsQueryResponse
@@ -546,6 +561,23 @@ class LogsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMi
raise UserAccessControlError("logs", "viewer")
+ @cached_property
+ def _custom_column_aliases(self) -> list[str]:
+ return [canonical_key(text) for text in self.query.customColumns or []]
+
+ def _custom_column_selects(self) -> list[ast.Expr]:
+ custom_columns = self.query.customColumns or []
+ if len(custom_columns) > MAX_CUSTOM_COLUMNS:
+ raise QueryError(f"Too many custom columns: {len(custom_columns)} (max {MAX_CUSTOM_COLUMNS})")
+ selects: list[ast.Expr] = []
+ for text, alias in zip(custom_columns, self._custom_column_aliases):
+ try:
+ expr = column_to_expr(text)
+ except (ValueError, ExposedHogQLError) as e:
+ raise QueryError(f"Invalid custom column {text!r}: {e}")
+ selects.append(ast.Alias(alias=alias, expr=expr))
+ return selects
+
def _calculate(self) -> LogsQueryResponse:
response = self.paginator.execute_hogql_query(
query_type="LogsQuery",
@@ -562,6 +594,7 @@ class LogsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMi
for result in response.results:
results.append(
{
+ **dict(zip(self._custom_column_aliases, result[_FIXED_COLUMN_COUNT:])),
"uuid": result[0],
"trace_id": result[1],
"span_id": result[2],
@@ -583,7 +616,11 @@ class LogsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMi
}
)
- return LogsQueryResponse(results=results, **self.paginator.response_params())
+ return LogsQueryResponse(
+ results=results,
+ columns=self._custom_column_aliases or None,
+ **self.paginator.response_params(),
+ )
def run(self, *args, **kwargs) -> LogsQueryResponse | CachedLogsQueryResponse:
response = super().run(*args, **kwargs)
@@ -628,6 +665,7 @@ class LogsQueryRunner(AnalyticsQueryRunner[LogsQueryResponse], LogsQueryRunnerMi
)
)
assert isinstance(query, ast.SelectQuery)
+ query.select.extend(self._custom_column_selects())
query.order_by = [
parse_order_expr(f"timestamp {order_dir}"),
parse_order_expr(f"uuid {order_dir}"),
diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.py
index 4730e7d1a565..e019b4003024 100644
--- a/products/logs/backend/presentation/views/api.py
+++ b/products/logs/backend/presentation/views/api.py
@@ -25,6 +25,8 @@ from posthog.schema import (
PropertyGroupFilter,
)
+from posthog.hogql.errors import QueryError
+
from posthog.api.documentation import _FallbackSerializer
from posthog.api.mixins import PydanticModelMixin
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
@@ -37,6 +39,7 @@ from posthog.models import User
from posthog.tasks.exporter import export_asset
from products.exports.backend.models.exported_asset import ExportedAsset
+from products.logs.backend.column_expressions import canonical_key
from products.logs.backend.count_query_runner import CountQueryRunner
from products.logs.backend.count_ranges_query_runner import (
DEFAULT_TARGET_BUCKETS,
@@ -54,7 +57,12 @@ from products.logs.backend.has_logs_query_runner import team_has_logs
from products.logs.backend.log_attributes_query_runner import LogAttributesQueryRunner
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.logs_query_runner import (
+ MAX_CUSTOM_COLUMNS,
+ 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
@@ -258,6 +266,17 @@ class _LogsQueryBodySerializer(serializers.Serializer):
default=False,
help_text="Omit the per-log attributes and resource_attributes maps from results to keep payloads compact. Defaults to false.",
)
+ customColumns = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ default=[],
+ help_text=(
+ "Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand "
+ "(`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression "
+ "(`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Aggregations and subqueries are rejected. "
+ "Values come back on each result row keyed by the aliases echoed in the response `columns` field."
+ ),
+ )
class _LogsQueryRequestSerializer(serializers.Serializer):
@@ -537,6 +556,15 @@ class _LogsQueryResponseSerializer(serializers.Serializer):
maxExportableLogs = serializers.IntegerField(
help_text="Maximum number of rows the `export` endpoint will produce — informational.",
)
+ columns = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Aliases for the requested `customColumns`, in request order. Each result row carries its "
+ "custom column values under these keys. Null when no custom columns were requested."
+ ),
+ )
class _LogsCountResponseSerializer(serializers.Serializer):
@@ -950,6 +978,13 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
after_cursor = query_data.get("after", None)
date_range = self.get_model(query_data.get("dateRange"), DateRange)
+ custom_columns = query_data.get("customColumns") or []
+ if len(custom_columns) > MAX_CUSTOM_COLUMNS:
+ return Response(
+ {"error": f"Too many custom columns: {len(custom_columns)} (max {MAX_CUSTOM_COLUMNS})"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
order_by = query_data.get("orderBy")
# Default to latest instead of erroring on invalid order_by
if order_by not in (LogsOrderBy.EARLIEST, LogsOrderBy.LATEST):
@@ -987,6 +1022,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
"resourceFingerprint": query_data.get("resourceFingerprint", None),
"limit": requested_limit + 1, # Fetch limit plus 1 to see if theres another page
"excludeAttributes": query_data.get("excludeAttributes", False),
+ "customColumns": custom_columns,
}
if live_logs_checkpoint:
logs_query_params["liveLogsCheckpoint"] = live_logs_checkpoint
@@ -1001,20 +1037,24 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
# Skip time-slicing for live tailing - we're always only looking at the most recent 1-2 minutes
# Note: cursor pagination no longer skips time-slicing because we narrow the date range
# to end at the cursor timestamp, allowing time-slicing to work on the remaining range.
- if live_logs_checkpoint:
- response = LogsQueryRunner(query, self.team).run(
- ExecutionMode.CALCULATE_BLOCKING_ALWAYS, analytics_props=analytics_props
- )
- results = list(response.results)
- else:
- results = list(
- time_sliced_results(
- runner=LogsQueryRunner(query, self.team),
- order_by_earliest=order_by == LogsOrderBy.EARLIEST,
- make_runner=make_runner,
- analytics_props=analytics_props,
+ try:
+ if live_logs_checkpoint:
+ response = LogsQueryRunner(query, self.team).run(
+ ExecutionMode.CALCULATE_BLOCKING_ALWAYS, analytics_props=analytics_props
)
- )
+ results = list(response.results)
+ else:
+ results = list(
+ time_sliced_results(
+ runner=LogsQueryRunner(query, self.team),
+ order_by_earliest=order_by == LogsOrderBy.EARLIEST,
+ make_runner=make_runner,
+ analytics_props=analytics_props,
+ )
+ )
+ except QueryError as e:
+ # A bad custom-column expression is re-raised by the runner as QueryError; keep it a clean 400.
+ return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
has_more = len(results) > requested_limit
results = results[:requested_limit] # Rm the +1 we used to check for another page
@@ -1052,6 +1092,7 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
"hasMore": has_more,
"nextCursor": next_cursor,
"maxExportableLogs": LOGS_MAX_EXPORT_ROWS,
+ "columns": [canonical_key(c) for c in custom_columns] or None,
},
status=200,
)
@@ -1509,6 +1550,13 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
if query_data is None:
return Response({"error": "No query provided"}, status=status.HTTP_400_BAD_REQUEST)
+ custom_columns = query_data.get("customColumns") or []
+ if len(custom_columns) > MAX_CUSTOM_COLUMNS:
+ return Response(
+ {"error": f"Too many custom columns: {len(custom_columns)} (max {MAX_CUSTOM_COLUMNS})"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
columns = request.data.get("columns") or []
filename = self._generate_export_filename(query_data)
diff --git a/products/logs/backend/test/test_column_expressions.py b/products/logs/backend/test/test_column_expressions.py
index 671a387e7ddf..e822f5981e1c 100644
--- a/products/logs/backend/test/test_column_expressions.py
+++ b/products/logs/backend/test/test_column_expressions.py
@@ -109,6 +109,21 @@ class TestColumnToExpr(SimpleTestCase):
("nested_aggregate", "upper(toString(sum(1)))"),
("subquery", "(SELECT 1)"),
("placeholder", "{cursor}"),
+ # Row-multiplying functions would expand a per-row column into many rows — a low-friction DoS.
+ ("array_join_row_multiplier", "arrayJoin(range(1000000000))"),
+ ("array_join_case_insensitive", "ARRAYJOIN([1, 2, 3])"),
+ ("nested_array_join", "toString(arrayJoin(range(10)))"),
+ # Value-generating functions build a huge per-row value from a small constant argument without
+ # multiplying rows — the row-multiplier check above misses them.
+ ("range_generator", "range(1000000000)"),
+ ("range_case_insensitive", "RANGE(10)"),
+ ("nested_range_generator", "length(range(1000000000))"),
+ ("repeat_generator", "repeat(body, 1000000000)"),
+ ("arraywithconstant_generator", "arrayWithConstant(1000000000, 'x')"),
+ # Window functions evaluate over a frame of rows, forcing ClickHouse to process every
+ # matching log before the page limit applies — same availability risk as aggregations.
+ ("window_row_number", "row_number() over (order by timestamp)"),
+ ("window_aggregate_over", "min(timestamp) over ()"),
]
)
def test_non_scalar_expressions_are_rejected(self, _name, text):
diff --git a/products/logs/backend/test/test_custom_columns.py b/products/logs/backend/test/test_custom_columns.py
new file mode 100644
index 000000000000..b60761c937e5
--- /dev/null
+++ b/products/logs/backend/test/test_custom_columns.py
@@ -0,0 +1,73 @@
+import os
+import json
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from posthog.schema import DateRange, LogsQuery
+
+from posthog.hogql.errors import QueryError
+
+from posthog.clickhouse.client import sync_execute
+
+from products.logs.backend.column_expressions import canonical_key
+from products.logs.backend.logs_query_runner import MAX_CUSTOM_COLUMNS, LogsQueryRunner
+
+# The shipped fixture log is timestamped 2025-12-16, service_name "argo-rollouts",
+# severity "info", with resource_attributes["k8s.container.name"] = "argo-rollouts-dashboard".
+DATE_FROM = "2025-12-16T00:00:00Z"
+DATE_TO = "2025-12-17T00:00:00Z"
+
+
+class TestLogsCustomColumns(ClickhouseTestMixin, APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = True
+
+ @classmethod
+ def setUpTestData(cls):
+ super().setUpTestData()
+ sync_execute("TRUNCATE TABLE IF EXISTS logs32")
+ with open(os.path.join(os.path.dirname(__file__), "test_logs.jsonnd")) as f:
+ log_item = json.loads(f.readline())
+ log_item["team_id"] = cls.team.id
+ sync_execute(f"INSERT INTO logs FORMAT JSONEachRow {json.dumps(log_item)}")
+
+ @classmethod
+ def tearDownClass(cls):
+ sync_execute("TRUNCATE TABLE IF EXISTS logs32")
+ super().tearDownClass()
+
+ def _run(self, custom_columns: list[str]):
+ query = LogsQuery(
+ dateRange=DateRange(date_from=DATE_FROM, date_to=DATE_TO),
+ serviceNames=["argo-rollouts"],
+ severityLevels=[],
+ filterGroup={"type": "AND", "values": []},
+ customColumns=custom_columns,
+ )
+ return LogsQueryRunner(query, self.team).run()
+
+ def test_custom_columns_resolve_and_align_to_aliases(self):
+ # A shorthand map lookup and a HogQL transform, appended after the fixed columns.
+ # Exact expected values fail if the positional result mapping (result[_FIXED_COLUMN_COUNT:])
+ # drifts off the fixed column count, or if either resolution tier breaks.
+ shorthand = "resource_attributes.k8s.container.name"
+ expression = "upper(service_name)"
+ response = self._run([shorthand, expression])
+
+ self.assertEqual(response.columns, [canonical_key(shorthand), canonical_key(expression)])
+ self.assertEqual(len(response.results), 1)
+ row = response.results[0]
+ self.assertEqual(row[canonical_key(shorthand)], "argo-rollouts-dashboard")
+ self.assertEqual(row[canonical_key(expression)], "ARGO-ROLLOUTS")
+
+ def test_no_custom_columns_leaves_columns_null(self):
+ # The frontend keys off a null `columns` to decide there are no custom columns to render.
+ response = self._run([])
+ self.assertIsNone(response.columns)
+ self.assertEqual(len(response.results), 1)
+
+ def test_too_many_custom_columns_rejected_by_runner(self):
+ # The cap is enforced in the runner so every LogsQuery entry point is bounded — including
+ # the CSV export worker, which copies query_data straight into a LogsQuery without the
+ # interactive endpoint's 400 check. Exceeding the cap must fail before the query runs.
+ with self.assertRaises(QueryError):
+ self._run(["service_name"] * (MAX_CUSTOM_COLUMNS + 1))
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 826685357614..21cad84bf51e 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -1265,6 +1265,8 @@ export interface _LogsQueryBodyApi {
after?: string
/** Omit the per-log attributes and resource_attributes maps from results to keep payloads compact. Defaults to false. */
excludeAttributes?: boolean
+ /** Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Aggregations and subqueries are rejected. Values come back on each result row keyed by the aliases echoed in the response `columns` field. */
+ customColumns?: string[]
}
export interface _LogsQueryRequestApi {
@@ -1328,6 +1330,11 @@ export interface _LogsQueryResponseApi {
nextCursor?: string | null
/** Maximum number of rows the `export` endpoint will produce — informational. */
maxExportableLogs: number
+ /**
+ * Aliases for the requested `customColumns`, in request order. Each result row carries its custom column values under these keys. Null when no custom columns were requested.
+ * @nullable
+ */
+ columns?: string[] | null
}
/**
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index 29ebbfca5835..606de2e79a78 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -908,6 +908,7 @@ export const logsQueryCreateBodyQueryOneServiceNamesDefault = []
export const logsQueryCreateBodyQueryOneFilterGroupDefault = []
export const logsQueryCreateBodyQueryOneLimitDefault = 100
export const logsQueryCreateBodyQueryOneExcludeAttributesDefault = false
+export const logsQueryCreateBodyQueryOneCustomColumnsDefault = []
export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({
query: zod
@@ -1003,6 +1004,12 @@ export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Omit the per-log attributes and resource_attributes maps from results to keep payloads compact. Defaults to false.'
),
+ customColumns: zod
+ .array(zod.string())
+ .default(logsQueryCreateBodyQueryOneCustomColumnsDefault)
+ .describe(
+ "Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Aggregations and subqueries are rejected. Values come back on each result row keyed by the aliases echoed in the response `columns` field."
+ ),
})
.describe('The logs query to execute.'),
})
diff --git a/pyproject.toml b/pyproject.toml
index 546119abdf90..bfc5beeb0550 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -542,6 +542,7 @@ ignore_imports = [
# logs presentation isolation (temporary): the moved viewsets still reach in-product
# internals directly. Removed by the follow-up that thins each viewset to go through
# the facade.
+ "products.logs.backend.presentation.views.api -> products.logs.backend.column_expressions",
"products.logs.backend.presentation.views.api -> products.logs.backend.count_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.count_ranges_query_runner",
"products.logs.backend.presentation.views.api -> products.logs.backend.group_by_query_runner",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0175251f99f2..cf628f7abdb5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -26826,6 +26826,8 @@ export namespace Schemas {
export interface LogsQuery {
/** Cursor for fetching the next page of results */
after?: string | null;
+ /** Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Values come back on each result row keyed by the aliases in `LogsQueryResponse.columns`. */
+ customColumns?: string[] | null;
dateRange: DateRange;
/** Omit the per-log `attributes` and `resource_attributes` maps from results to keep payloads compact */
excludeAttributes?: boolean | null;
@@ -56426,6 +56428,8 @@ export namespace Schemas {
after?: string;
/** Omit the per-log attributes and resource_attributes maps from results to keep payloads compact. Defaults to false. */
excludeAttributes?: boolean;
+ /** Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Aggregations and subqueries are rejected. Values come back on each result row keyed by the aliases echoed in the response `columns` field. */
+ customColumns?: string[];
}
export interface _LogsQueryRequest {
@@ -56452,6 +56456,11 @@ export namespace Schemas {
nextCursor?: string | null;
/** Maximum number of rows the `export` endpoint will produce — informational. */
maxExportableLogs: number;
+ /**
+ * Aliases for the requested `customColumns`, in request order. Each result row carries its custom column values under these keys. Null when no custom columns were requested.
+ * @nullable
+ */
+ columns?: string[] | null;
}
export interface _LogsServiceActiveRule {
diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.ts
index 5677eee0e1de..dff3c9b11741 100644
--- a/services/mcp/src/generated/logs/api.ts
+++ b/services/mcp/src/generated/logs/api.ts
@@ -4098,6 +4098,7 @@ export const logsQueryCreateBodyQueryOneServiceNamesDefault = []
export const logsQueryCreateBodyQueryOneFilterGroupDefault = []
export const logsQueryCreateBodyQueryOneLimitDefault = 100
export const logsQueryCreateBodyQueryOneExcludeAttributesDefault = false
+export const logsQueryCreateBodyQueryOneCustomColumnsDefault = []
export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({
query: zod
@@ -4193,6 +4194,12 @@ export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Omit the per-log attributes and resource_attributes maps from results to keep payloads compact. Defaults to false.'
),
+ customColumns: zod
+ .array(zod.string())
+ .default(logsQueryCreateBodyQueryOneCustomColumnsDefault)
+ .describe(
+ "Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Aggregations and subqueries are rejected. Values come back on each result row keyed by the aliases echoed in the response `columns` field."
+ ),
})
.describe('The logs query to execute.'),
})
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
index dbb2ebb95f78..c55b41ee180b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
@@ -8,6 +8,14 @@
"description": "Pagination cursor from previous response.",
"type": "string"
},
+ "customColumns": {
+ "default": [],
+ "description": "Custom column expressions evaluated per log row. Each entry is either a source-prefixed shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`). Aggregations and subqueries are rejected. Values come back on each result row keyed by the aliases echoed in the response `columns` field.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"dateRange": {
"description": "Date range for the query. Defaults to last hour.",
"properties": {