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(metrics): pivot from a metric to its logs and traces (#89770)

Daniel Visca9e3b36a3612f
diff --git a/products/metrics/frontend/components/MetricsRelatedMenu.tsx b/products/metrics/frontend/components/MetricsRelatedMenu.tsx
new file mode 100644
index 000000000000..979ceb8385fc
--- /dev/null
+++ b/products/metrics/frontend/components/MetricsRelatedMenu.tsx
@@ -0,0 +1,80 @@
+import { useValues } from 'kea'
+
+import { LemonButton, LemonMenu, LemonMenuItem, LemonMenuItems } from '@posthog/lemon-ui'
+
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import { serviceViewerUrl } from 'products/logs/frontend/components/LogsServices/serviceViewerUrl'
+import { tracingUrlForService } from 'products/tracing/frontend/traceLinks'
+
+import { metricsViewerLogic } from './metricsViewerLogic'
+
+/**
+ * The metric -> logs / traces pivot.
+ *
+ * Both destinations inherit the chart's service scope and time window, so the jump lands on the
+ * same slice of the same incident. Where the metric carries exemplars there is an exact
+ * metric -> trace link already (the chart's markers and the Samples tab); this covers the case
+ * where all you have is a service and a window.
+ */
+export function MetricsRelatedMenu(): JSX.Element {
+ const { correlationServices, dateFrom, dateTo } = useValues(metricsViewerLogic)
+
+ const logsDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.Logs, AccessControlLevel.Viewer)
+ const tracingDisabledReason = getAccessControlDisabledReason(
+ AccessControlResourceType.Tracing,
+ AccessControlLevel.Viewer
+ )
+
+ const dateRange = { date_from: dateFrom, date_to: dateTo }
+
+ const itemsForService = (serviceName: string): LemonMenuItem[] => [
+ {
+ label: 'Logs',
+ to: serviceViewerUrl(serviceName, { dateRange }),
+ disabledReason: logsDisabledReason,
+ },
+ {
+ label: 'Error logs',
+ to: serviceViewerUrl(serviceName, { dateRange, severityLevels: ['error'] }),
+ disabledReason: logsDisabledReason,
+ },
+ {
+ label: 'Traces',
+ to: tracingUrlForService(serviceName, { dateRange }),
+ disabledReason: tracingDisabledReason,
+ },
+ ]
+
+ // One service reads better as a flat list; several need naming, or the items are ambiguous.
+ const items: LemonMenuItems =
+ correlationServices.length === 1
+ ? itemsForService(correlationServices[0])
+ : correlationServices.map((serviceName) => ({
+ title: serviceName,
+ items: itemsForService(serviceName),
+ }))
+
+ if (!correlationServices.length) {
+ return (
+ <LemonButton
+ size="small"
+ type="secondary"
+ disabledReason="Filter or group by a service to jump to its logs and traces"
+ data-attr="metrics-viewer-related"
+ >
+ Related
+ </LemonButton>
+ )
+ }
+
+ return (
+ <LemonMenu items={items}>
+ <LemonButton size="small" type="secondary" data-attr="metrics-viewer-related">
+ Related
+ </LemonButton>
+ </LemonMenu>
+ )
+}
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index f4d8c917e553..75448cccdf8a 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -47,6 +47,7 @@ import { MetricNameFilter } from './MetricNameFilter'
import { metricNamePickerLogic } from './metricNamePickerLogic'
import { type MetricsExemplar } from './MetricsExemplarMarkers'
import { MetricsLogsSourceTag } from './MetricsLogsSourceTag'
+import { MetricsRelatedMenu } from './MetricsRelatedMenu'
import { metricsSamplesLogic } from './metricsSamplesLogic'
import { MetricsSamplesPanel } from './MetricsSamplesPanel'
import { MetricsSeriesChart } from './MetricsSeriesChart'
@@ -317,6 +318,7 @@ export const MetricsViewer = (): JSX.Element => {
disabledReason={metricsViewerDisabledReason}
/>
<MetricsGroupByButton disabledReason={metricsViewerDisabledReason} />
+ <MetricsRelatedMenu />
{anomalyBadge && <MetricsAnomalyTag anomaly={anomalyBadge} />}
<MetricsLogsSourceTag metricName={metricName} />
</div>
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 323a9f50eadf..3a6fdbe30994 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -34,6 +34,8 @@ import { canCreateMetricsInsight, canViewMetrics } from 'products/metrics/fronte
import type { Node } from '../../../../frontend/src/queries/schema/schema-general'
import type { _MetricNameApi } from '../generated/api.schemas'
+import { EMPTY_SERVICE_PATTERN, SERVICE_NAME_KEY } from '../metricsAttributes'
+import { correlationServiceNames } from '../metricsLinks'
import { metricNamePickerLogic } from './metricNamePickerLogic'
import type { MetricNameItem } from './metricNamePickerLogic'
import type { MetricsChartSeries } from './metricsSeries'
@@ -48,6 +50,8 @@ export const METRIC_AGGREGATIONS: MetricAggregation[] = ['sum', 'avg', 'count',
export const isMetricAggregation = (value: unknown): value is MetricAggregation =>
typeof value === 'string' && METRIC_AGGREGATIONS.includes(value as MetricAggregation)
+export { EMPTY_SERVICE_PATTERN, SERVICE_NAME_KEY }
+
export type MetricsViewerSeries = _MetricSeriesApi
// Display shape for the "vs baseline" anomaly badge (null = no anomaly / flat metric).
@@ -141,14 +145,6 @@ const propertyFilterToMetricFilter = (filter: UniversalFilterValue): _MetricFilt
const flattenFilterValues = (group: UniversalFiltersGroup): UniversalFilterValue[] =>
group.values.flatMap((value) => (isUniversalGroupFilterLike(value) ? flattenFilterValues(value) : [value]))
-// Ingestion promotes `service.name` to its own column, so it is the one label the
-// picker can be narrowed by cheaply — see MetricNamesQueryRunner.
-export const SERVICE_NAME_KEY = 'service_name'
-
-// The anchored regex standing in for senders that set no service name: the empty
-// string cannot survive the filter pipeline, which drops empty chip values.
-export const EMPTY_SERVICE_PATTERN = '^$'
-
/** The services a chip pins the query to, or `[]` when it isn't a membership test. */
const serviceChipValues = (chip: UniversalFilterValue): string[] => {
const operator = 'operator' in chip ? chip.operator : undefined
@@ -195,6 +191,7 @@ export interface metricsViewerLogicValues {
}[]
attributeKeyOptionsLoading: boolean
chartSeries: MetricsChartSeries[]
+ correlationServices: string[]
dateFrom: string | null
dateTo: string | null
filterGroup: UniversalFiltersGroup
@@ -383,6 +380,7 @@ export interface metricsViewerLogicMeta {
) => MetricsQuery | null
queryFilters: (filterGroup: UniversalFiltersGroup) => _MetricFilterApi[]
selectedServices: (filterGroup: UniversalFiltersGroup) => string[]
+ correlationServices: (selectedServices: string[], queryResults: _MetricSeriesApi[]) => string[]
attributeEndpointFilters: (dateFrom: string | null, dateTo: string | null) => Record<string, string>
chartSeries: (queryResults: _MetricSeriesApi[]) => MetricsChartSeries[]
hasResults: (queryResults: _MetricSeriesApi[]) => boolean
@@ -810,6 +808,16 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
return serviceChipValues(chips[0])
},
],
+ // Services the logs and traces pivots can be scoped to: the pinned service filter, or
+ // failing that whichever services the chart is grouped by.
+ correlationServices: [
+ (s) => [s.selectedServices, s.queryResults],
+ (selectedServices: string[], results: MetricsViewerSeries[]): string[] =>
+ correlationServiceNames(
+ selectedServices,
+ results.map((series) => series.labels)
+ ),
+ ],
// Scopes the filter bar's key/value suggestions to the viewer's window; splatted onto the
// taxonomic endpoints as query params.
attributeEndpointFilters: [
diff --git a/products/metrics/frontend/metricsAttributes.ts b/products/metrics/frontend/metricsAttributes.ts
new file mode 100644
index 000000000000..79c05490fc12
--- /dev/null
+++ b/products/metrics/frontend/metricsAttributes.ts
@@ -0,0 +1,12 @@
+// Attribute keys shared by the viewer's filter bar and the cross-product link builders. A leaf
+// module on purpose: metricsLinks and metricsViewerLogic both need these, and importing one from
+// the other would put a kea logic in an import cycle.
+
+/** Ingestion promotes `service.name` to its own column, so this is the one label queries can narrow by cheaply. */
+export const SERVICE_NAME_KEY = 'service_name'
+
+/**
+ * The anchored regex standing in for senders that set no service name: the empty string cannot
+ * survive the filter pipeline, which drops empty chip values.
+ */
+export const EMPTY_SERVICE_PATTERN = '^$'
diff --git a/products/metrics/frontend/metricsLinks.test.ts b/products/metrics/frontend/metricsLinks.test.ts
index cd368bb113a9..9196454a6b7c 100644
--- a/products/metrics/frontend/metricsLinks.test.ts
+++ b/products/metrics/frontend/metricsLinks.test.ts
@@ -2,7 +2,7 @@ import { combineUrl } from 'kea-router'
import { FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'
-import { metricUrl, metricsUrlForService } from './metricsLinks'
+import { correlationServiceNames, metricUrl, metricsUrlForService } from './metricsLinks'
describe('metricsLinks', () => {
const paramsOf = (url: string): Record<string, any> => combineUrl(url).searchParams
@@ -68,4 +68,47 @@ describe('metricsLinks', () => {
dateFrom: '-30m',
})
})
+
+ describe('correlationServiceNames', () => {
+ // Which services the logs/traces pivot offers. Getting this wrong sends someone to an
+ // empty log view during an incident, which teaches them not to click it again.
+ it('prefers the services the filter bar pinned', () => {
+ expect(correlationServiceNames(['checkout'], [{ service_name: 'billing' }])).toEqual(['checkout'])
+ })
+
+ it('falls back to the services the chart is grouped by', () => {
+ expect(correlationServiceNames([], [{ service_name: 'billing' }, { service_name: 'checkout' }])).toEqual([
+ 'billing',
+ 'checkout',
+ ])
+ })
+
+ it.each([['service_name'], ['service.name']])('reads the %s group-by label', (key) => {
+ expect(correlationServiceNames([], [{ [key]: 'checkout' }])).toEqual(['checkout'])
+ })
+
+ it('de-duplicates services split across several series', () => {
+ expect(
+ correlationServiceNames(
+ [],
+ [
+ { service_name: 'checkout', http_status: '200' },
+ { service_name: 'checkout', http_status: '500' },
+ ]
+ )
+ ).toEqual(['checkout'])
+ })
+
+ it.each([
+ ['no scope at all', [] as string[], [{ http_status: '200' }]],
+ ['the unknown-service chip', [''], []],
+ ])('offers nothing for %s, rather than a link to everything', (_name, selected, labels) => {
+ expect(correlationServiceNames(selected, labels)).toEqual([])
+ })
+
+ it('caps the list so a wide group-by cannot render hundreds of menu items', () => {
+ const labels = Array.from({ length: 30 }, (_, i) => ({ service_name: `svc-${i}` }))
+ expect(correlationServiceNames([], labels)).toHaveLength(12)
+ })
+ })
})
diff --git a/products/metrics/frontend/metricsLinks.ts b/products/metrics/frontend/metricsLinks.ts
index e5d73d05be6e..fda7591b7fcf 100644
--- a/products/metrics/frontend/metricsLinks.ts
+++ b/products/metrics/frontend/metricsLinks.ts
@@ -4,7 +4,7 @@ import { urls } from 'scenes/urls'
import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
-import { SERVICE_NAME_KEY } from './components/metricsViewerLogic'
+import { SERVICE_NAME_KEY } from './metricsAttributes'
/**
* The metrics viewer's URL contract, in one place.
@@ -76,6 +76,44 @@ export const metricUrl = (params: MetricLinkParams): string => {
return combineUrl(urls.metrics(), searchParams).url
}
+/**
+ * Ingest promotes `service.name` to a column, but a group-by carries whichever spelling the user
+ * picked, so both reach the results as label keys.
+ */
+const SERVICE_LABEL_KEYS = [SERVICE_NAME_KEY, 'service.name']
+
+/** At most this many services in the Related menu — a wide group-by would otherwise fill the screen. */
+export const MAX_CORRELATION_SERVICES = 12
+
+/**
+ * The services a logs or traces pivot can be scoped to, given what the chart currently shows.
+ *
+ * A pinned service filter is the user's stated scope, so it wins. Failing that, a chart grouped by
+ * service names its own services. With neither, there is nothing honest to link to: an unscoped
+ * jump into logs lands on every service in the project, which reads as a broken link.
+ */
+export const correlationServiceNames = (
+ selectedServices: string[],
+ seriesLabels: Record<string, string>[]
+): string[] => {
+ // `selectedServices` reports the "unknown service" chip as an empty string, which is a real
+ // selection in metrics but cannot be expressed as a logs or traces service filter.
+ const pinned = selectedServices.filter(Boolean)
+ if (pinned.length) {
+ return pinned.slice(0, MAX_CORRELATION_SERVICES)
+ }
+
+ const grouped = new Set<string>()
+ for (const labels of seriesLabels) {
+ for (const key of SERVICE_LABEL_KEYS) {
+ if (labels[key]) {
+ grouped.add(labels[key])
+ }
+ }
+ }
+ return [...grouped].sort().slice(0, MAX_CORRELATION_SERVICES)
+}
+
/** "Show me this service's metrics", the pivot Logs and Tracing offer. */
export const metricsUrlForService = (serviceName: string, params: Omit<MetricLinkParams, 'filterGroup'> = {}): string =>
metricUrl({
diff --git a/products/tracing/frontend/traceLinks.test.ts b/products/tracing/frontend/traceLinks.test.ts
index 567bc0fcbedd..a9919c372445 100644
--- a/products/tracing/frontend/traceLinks.test.ts
+++ b/products/tracing/frontend/traceLinks.test.ts
@@ -1,4 +1,6 @@
-import { traceLookupDateRange, traceUrl } from './traceLinks'
+import { combineUrl } from 'kea-router'
+
+import { traceLookupDateRange, traceUrl, tracingUrlForService } from './traceLinks'
describe('traceLinks', () => {
it.each([
@@ -20,4 +22,23 @@ describe('traceLinks', () => {
date_to: '2026-06-11T09:00:00.000Z',
})
})
+
+ describe('tracingUrlForService', () => {
+ const paramsOf = (url: string): Record<string, any> => combineUrl(url).searchParams
+
+ it('carries the service as a list, so a name with a comma stays one service', () => {
+ // tracingSceneLogic reads this back through parseTagsFilter, which splits a bare
+ // string on commas — 'checkout,v2' would arrive as two services.
+ expect(paramsOf(tracingUrlForService('checkout,v2')).serviceNames).toEqual(['checkout,v2'])
+ })
+
+ it('carries the window the caller was looking at', () => {
+ const url = tracingUrlForService('checkout', { dateRange: { date_from: '-30m', date_to: null } })
+ expect(JSON.parse(paramsOf(url).dateRange)).toEqual({ date_from: '-30m', date_to: null })
+ })
+
+ it('omits the window when the caller has none', () => {
+ expect(paramsOf(tracingUrlForService('checkout'))).not.toHaveProperty('dateRange')
+ })
+ })
})
diff --git a/products/tracing/frontend/traceLinks.ts b/products/tracing/frontend/traceLinks.ts
index 21acbccbd8d7..16c39000cb4f 100644
--- a/products/tracing/frontend/traceLinks.ts
+++ b/products/tracing/frontend/traceLinks.ts
@@ -3,9 +3,13 @@
// root timestamp so a cold load can bound the ClickHouse lookup (the table is time-keyed and OTel
// trace ids embed no timestamp — an unhinted id lookup would scan the whole retention window).
+import { combineUrl } from 'kea-router'
+
import { dayjs } from 'lib/dayjs'
import { urls } from 'scenes/urls'
+import type { DateRange } from '~/queries/schema/schema-general'
+
export interface TraceLinkParams {
traceId: string
spanId?: string | null
@@ -30,6 +34,18 @@ export function absoluteTraceUrl(params: TraceLinkParams): string {
return urls.absolute(traceUrl(params))
}
+/**
+ * Spans for one service over a window — the pivot other products offer when they know a service
+ * and a time range but no trace id. The service goes in as a list because `tracingSceneLogic`
+ * reads it back through `parseTagsFilter`, which splits a bare string on commas.
+ */
+export function tracingUrlForService(serviceName: string, { dateRange }: { dateRange?: DateRange } = {}): string {
+ return combineUrl(urls.tracing(), {
+ serviceNames: [serviceName],
+ ...(dateRange ? { dateRange: JSON.stringify(dateRange) } : {}),
+ }).url
+}
+
/** The window a `ts`-hinted cold load queries: ±1h is generous for any single trace's spans. */
export function traceLookupDateRange(ts: string): { date_from: string; date_to: string } {
return {