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): link a log to its trace and a service to its metrics (#89776)

Daniel Visca68f87867e7e7
diff --git a/products/logs/frontend/components/LogsServices/LogsServicesV2.tsx b/products/logs/frontend/components/LogsServices/LogsServicesV2.tsx
index 64855070402c..c71860d3f7c8 100644
--- a/products/logs/frontend/components/LogsServices/LogsServicesV2.tsx
+++ b/products/logs/frontend/components/LogsServices/LogsServicesV2.tsx
@@ -70,7 +70,12 @@ export function LogsServicesV2(): JSX.Element {
{viewMode === 'grid' ? (
<ServicesGrid />
) : (
- <ServicesList services={sortedServices} loading={servicesDataLoading} searchTerm={searchTerm} />
+ <ServicesList
+ services={sortedServices}
+ loading={servicesDataLoading}
+ searchTerm={searchTerm}
+ dateFrom={dateFrom}
+ />
)}
</div>
</div>
diff --git a/products/logs/frontend/components/LogsServices/ServicesList.test.tsx b/products/logs/frontend/components/LogsServices/ServicesList.test.tsx
index 2189eaa65b23..ada09e624a74 100644
--- a/products/logs/frontend/components/LogsServices/ServicesList.test.tsx
+++ b/products/logs/frontend/components/LogsServices/ServicesList.test.tsx
@@ -1,8 +1,11 @@
import { render } from '@testing-library/react'
import type { SizeProps } from 'lib/components/AutoSizer/AutoSizer'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { initKeaTests } from '~/test/init'
+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
import type { ServiceRow } from './logsServicesLogic'
import { ServicesList } from './ServicesList'
@@ -31,8 +34,21 @@ describe('ServicesList', () => {
initKeaTests()
})
- const renderList = (services: ServiceRow[] = SERVICES): HTMLElement =>
- render(<ServicesList services={services} loading={false} searchTerm="" />).container
+ const renderList = (services: ServiceRow[] = SERVICES, dateFrom = '-1h'): HTMLElement =>
+ render(<ServicesList services={services} loading={false} searchTerm="" dateFrom={dateFrom} />).container
+
+ /** The metrics link is gated on the alpha flag and on metrics access, so a row only shows it for both. */
+ const enableMetricsLink = (): void => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ resource_access_control: {
+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
+ [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,
+ },
+ } as AppContext
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.METRICS]: true })
+ }
it('keeps the DOM bounded by the viewport, not by the number of services', () => {
const rows = renderList().querySelectorAll('[data-attr="logs-services-row"]')
@@ -64,4 +80,15 @@ describe('ServicesList', () => {
it('states how many services matched and how far they scroll', () => {
expect(renderList().textContent).toContain('2,400 services, about 134 screens')
})
+
+ // Metrics defaults to the last hour. Without the window the user picked here, a service
+ // busy over seven days opens on an hour of chart and reads as though it has no traffic.
+ it('opens metrics on the window the services list is showing', () => {
+ enableMetricsLink()
+ const href = renderList([service('checkout')], '-7d')
+ .querySelector('[data-attr="logs-services-row-metrics"]')
+ ?.getAttribute('href')
+
+ expect(href).toContain('dateFrom=-7d')
+ })
})
diff --git a/products/logs/frontend/components/LogsServices/ServicesList.tsx b/products/logs/frontend/components/LogsServices/ServicesList.tsx
index 91fe523189a5..ad6436e3ef49 100644
--- a/products/logs/frontend/components/LogsServices/ServicesList.tsx
+++ b/products/logs/frontend/components/LogsServices/ServicesList.tsx
@@ -9,6 +9,11 @@ import { SizeProps } from 'lib/components/AutoSizer/AutoSizer'
import { cn } from 'lib/utils/css-classes'
import { humanFriendlyLargeNumber, humanFriendlyNumber } from 'lib/utils/numbers'
+import {
+ useCanViewServiceMetrics,
+ ViewServiceMetricsButton,
+} from 'products/metrics/frontend/components/ViewServiceMetricsButton'
+
import { NO_SERVICE_LABEL, ServiceRow } from './logsServicesLogic'
import { copyServiceDeepLink, serviceViewerUrl } from './serviceViewerUrl'
@@ -21,19 +26,29 @@ const HEADER_HEIGHT = 28
/** Shared by the header and every row so the columns line up either side of the scroller. */
const COLUMN_TEMPLATE = 'grid grid-cols-[minmax(0,1fr)_6rem_5rem_12rem] items-center gap-2'
+/**
+ * Width the row actions reserve, so the header and the no-service placeholder line up with a
+ * normal row. The metrics link is flag-gated, so it changes the count — and two buttons also sit
+ * either side of the row's `gap-2`, which the reservation has to include.
+ */
+const actionsWidthClass = (withMetricsLink: boolean): string => (withMetricsLink ? 'w-14' : 'w-6')
+
interface ServicesListProps {
services: ServiceRow[]
loading: boolean
/** Both the empty state and the subtitle read differently for a search result than for the whole project. */
searchTerm: string
+ /** The window these counts cover, so the metrics link opens on it rather than the metrics default. */
+ dateFrom: string
}
/**
* Every service in the project, in one scroller. The aggregates query costs the same whether
* it returns 25 rows or all of them, because the LIMIT lands after the GROUP BY.
*/
-export function ServicesList({ services, loading, searchTerm }: ServicesListProps): JSX.Element {
- const rowProps = useMemo(() => ({ services }), [services])
+export function ServicesList({ services, loading, searchTerm, dateFrom }: ServicesListProps): JSX.Element {
+ const withMetricsLink = useCanViewServiceMetrics()
+ const rowProps = useMemo(() => ({ services, withMetricsLink, dateFrom }), [services, withMetricsLink, dateFrom])
if (loading && services.length === 0) {
return (
@@ -67,7 +82,7 @@ export function ServicesList({ services, loading, searchTerm }: ServicesListProp
<div className="h-6 shrink-0 text-xs text-muted px-2">
{densitySubtitle(services.length, screenCount(services.length, listHeight), !!searchTerm)}
</div>
- <ServicesListHeader />
+ <ServicesListHeader withMetricsLink={withMetricsLink} />
<List<ServicesListRowProps>
// eslint-disable-next-line react/forbid-dom-props
style={{ width, height: listHeight }}
@@ -95,7 +110,7 @@ function densitySubtitle(serviceCount: number, screens: number, searching: boole
return screens <= 1 ? label : `${label}, about ${humanFriendlyNumber(screens)} screens`
}
-function ServicesListHeader(): JSX.Element {
+function ServicesListHeader({ withMetricsLink }: { withMetricsLink: boolean }): JSX.Element {
return (
<div className="h-7 shrink-0 flex items-center gap-2 pr-2 border-b text-xs font-semibold text-secondary uppercase tracking-wide">
<div className={cn(COLUMN_TEMPLATE, 'flex-1 min-w-0 pl-2')}>
@@ -104,14 +119,16 @@ function ServicesListHeader(): JSX.Element {
<span className="text-right">Error rate</span>
<span>Rules</span>
</div>
- {/* Matches the share button, which has no column title of its own. */}
- <span className="w-6 shrink-0" />
+ {/* Matches the row actions, which have no column title of their own. */}
+ <span className={cn('shrink-0', actionsWidthClass(withMetricsLink))} />
</div>
)
}
interface ServicesListRowProps {
services: ServiceRow[]
+ withMetricsLink: boolean
+ dateFrom: string
}
function ServicesListRow({
@@ -119,6 +136,8 @@ function ServicesListRow({
index,
style,
services,
+ withMetricsLink,
+ dateFrom,
}: {
ariaAttributes: { 'aria-posinset': number; 'aria-setsize': number; role: 'listitem' }
index: number
@@ -158,18 +177,28 @@ function ServicesListRow({
</Tooltip>
)}
{deepLinkable ? (
- <Tooltip title="Copy a link to the viewer filtered to this service">
- <LemonButton
+ <>
+ <ViewServiceMetricsButton
+ serviceName={service.service_name}
+ dateFrom={dateFrom}
size="xsmall"
noPadding
- icon={<IconShare />}
- onClick={() => copyServiceDeepLink(service.service_name)}
- data-attr="logs-services-row-share"
+ iconOnly
+ data-attr="logs-services-row-metrics"
/>
- </Tooltip>
+ <Tooltip title="Copy a link to the viewer filtered to this service">
+ <LemonButton
+ size="xsmall"
+ noPadding
+ icon={<IconShare />}
+ onClick={() => copyServiceDeepLink(service.service_name)}
+ data-attr="logs-services-row-share"
+ />
+ </Tooltip>
+ </>
) : (
- /* Holds the share button's width so the columns line up across every row. */
- <span className="w-6 shrink-0" />
+ /* Holds the row actions' width so the columns line up across every row. */
+ <span className={cn('shrink-0', actionsWidthClass(withMetricsLink))} />
)}
</div>
)
diff --git a/products/logs/frontend/components/LogsViewer/LogDetailsModal/LogDetailsModal.tsx b/products/logs/frontend/components/LogsViewer/LogDetailsModal/LogDetailsModal.tsx
index 9a38fcbac96e..81e2647767d0 100644
--- a/products/logs/frontend/components/LogsViewer/LogDetailsModal/LogDetailsModal.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogDetailsModal/LogDetailsModal.tsx
@@ -13,6 +13,7 @@ import { PropertyFilterType, PropertyOperator } from '~/types'
import { CopyLogButton, copyLogRaw } from 'products/logs/frontend/components/LogsViewer/CopyLogButton'
import { LogContextSelector } from 'products/logs/frontend/components/LogsViewer/LogContextSelector/LogContextSelector'
import { LogDetailsTabContent } from 'products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/Details/LogDetailsTab'
+import { ViewTraceButton } from 'products/tracing/frontend/components/ViewTraceButton'
import { logsViewerLogic } from '../logsViewerLogic'
import { LogComments } from './LogComments'
@@ -134,15 +135,25 @@ export function LogDetailsModal({ timezone }: LogDetailsModalProps): JSX.Element
</div>
</div>
</div>
- {sessionId && (
- <ViewRecordingButton
- sessionId={sessionId}
+ <div className="flex items-center gap-1">
+ <ViewTraceButton
+ traceId={selectedLog.trace_id}
+ spanId={selectedLog.span_id}
timestamp={selectedLog.timestamp}
size="xsmall"
- openPlayerIn={RecordingPlayerType.Modal}
- checkRecordingExists
+ type="secondary"
+ data-attr="logs-details-view-trace"
/>
- )}
+ {sessionId && (
+ <ViewRecordingButton
+ sessionId={sessionId}
+ timestamp={selectedLog.timestamp}
+ size="xsmall"
+ openPlayerIn={RecordingPlayerType.Modal}
+ checkRecordingExists
+ />
+ )}
+ </div>
</div>
</LemonDrawer.Header>
<LemonDrawer.Content>
diff --git a/products/metrics/frontend/components/ViewServiceMetricsButton.test.tsx b/products/metrics/frontend/components/ViewServiceMetricsButton.test.tsx
new file mode 100644
index 000000000000..30ef0138f086
--- /dev/null
+++ b/products/metrics/frontend/components/ViewServiceMetricsButton.test.tsx
@@ -0,0 +1,61 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
+
+import { ViewServiceMetricsButton } from './ViewServiceMetricsButton'
+
+describe('ViewServiceMetricsButton', () => {
+ const setAccess = (level: AccessControlLevel | undefined): void => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ resource_access_control: {
+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
+ [AccessControlResourceType.Metrics]: level,
+ },
+ } as AppContext
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ featureFlagLogic.mount()
+ })
+
+ afterEach(() => cleanup())
+
+ const renderButton = ({ flagOn = true, ...props }: any): void => {
+ featureFlagLogic.actions.setFeatureFlags([], flagOn ? { [FEATURE_FLAGS.METRICS]: true } : {})
+ render(
+ <Provider>
+ <ViewServiceMetricsButton {...props} />
+ </Provider>
+ )
+ }
+
+ // Metrics is in private alpha behind a flag. A link rendered without it lands on the waitlist
+ // screen, not a chart — a dead end reached from a GA product.
+ it.each([
+ ['the metrics flag is off', { serviceName: 'checkout', flagOn: false }, AccessControlLevel.Viewer],
+ ['the user cannot view metrics', { serviceName: 'checkout' }, undefined],
+ ['there is no service name', { serviceName: '' }, AccessControlLevel.Viewer],
+ ])('renders nothing when %s', (_name, props, level) => {
+ setAccess(level)
+ renderButton(props)
+ expect(screen.queryByText('View metrics')).not.toBeInTheDocument()
+ })
+
+ it('links to the service, carrying the window the caller was on', () => {
+ setAccess(AccessControlLevel.Viewer)
+ renderButton({ serviceName: 'checkout', dateFrom: '-30m' })
+
+ const href = screen.getByText('View metrics').closest('a')?.getAttribute('href')
+ expect(href).toContain('dateFrom=-30m')
+ expect(href).toContain('checkout')
+ })
+})
diff --git a/products/metrics/frontend/components/ViewServiceMetricsButton.tsx b/products/metrics/frontend/components/ViewServiceMetricsButton.tsx
new file mode 100644
index 000000000000..132d9f7ff161
--- /dev/null
+++ b/products/metrics/frontend/components/ViewServiceMetricsButton.tsx
@@ -0,0 +1,61 @@
+import { IconGraph } from '@posthog/icons'
+import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+
+import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'
+import { metricsUrlForService } from 'products/metrics/frontend/metricsLinks'
+
+export interface ViewServiceMetricsButtonProps extends Pick<
+ LemonButtonProps,
+ 'size' | 'type' | 'className' | 'noPadding' | 'data-attr'
+> {
+ serviceName: string | null | undefined
+ /** Opens the viewer on the window the caller was looking at, rather than the metrics default. */
+ dateFrom?: string | null
+ dateTo?: string | null
+ iconOnly?: boolean
+}
+
+/**
+ * Whether a metrics link would actually reach a chart for this team.
+ *
+ * Exported for callers that reserve layout space for the button, so a hidden button does not leave
+ * a column misaligned. `ViewServiceMetricsButton` applies the same check itself.
+ */
+export function useCanViewServiceMetrics(): boolean {
+ const metricsEnabled = useFeatureFlag('METRICS')
+ return metricsEnabled && canViewMetrics()
+}
+
+/**
+ * "Show me this service's metrics", for Logs and Tracing to drop into a service row or a span.
+ *
+ * Metrics owns this gate rather than each caller, because the product is in private alpha behind a
+ * flag: a link rendered without it lands on the waitlist screen instead of a chart, and callers
+ * would each have to remember that.
+ */
+export function ViewServiceMetricsButton({
+ serviceName,
+ dateFrom,
+ dateTo,
+ iconOnly,
+ ...buttonProps
+}: ViewServiceMetricsButtonProps): JSX.Element | null {
+ const canViewServiceMetrics = useCanViewServiceMetrics()
+
+ if (!serviceName || !canViewServiceMetrics) {
+ return null
+ }
+
+ return (
+ <LemonButton
+ icon={<IconGraph />}
+ to={metricsUrlForService(serviceName, { dateFrom, dateTo })}
+ tooltip={iconOnly ? `Metrics for ${serviceName}` : undefined}
+ {...buttonProps}
+ >
+ {iconOnly ? undefined : 'View metrics'}
+ </LemonButton>
+ )
+}
diff --git a/products/tracing/frontend/components/ViewTraceButton.test.tsx b/products/tracing/frontend/components/ViewTraceButton.test.tsx
new file mode 100644
index 000000000000..8b52f9144daa
--- /dev/null
+++ b/products/tracing/frontend/components/ViewTraceButton.test.tsx
@@ -0,0 +1,66 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { Provider } from 'kea'
+
+import { initKeaTests } from '~/test/init'
+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'
+
+import { ViewTraceButton } from './ViewTraceButton'
+
+describe('ViewTraceButton', () => {
+ beforeEach(() => {
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ resource_access_control: {
+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,
+ [AccessControlResourceType.Tracing]: AccessControlLevel.Viewer,
+ },
+ } as AppContext
+ initKeaTests()
+ })
+
+ afterEach(() => cleanup())
+
+ const renderButton = (props: Parameters<typeof ViewTraceButton>[0]): void => {
+ render(
+ <Provider>
+ <ViewTraceButton {...props} />
+ </Provider>
+ )
+ }
+
+ // A log row without a trace is the common case, not an edge case. Rendering the button anyway
+ // would link to `/tracing?trace=`, and one dead link teaches people to stop clicking it.
+ it.each([
+ ['an absent trace id', undefined],
+ ['an empty trace id', ''],
+ ['a null trace id', null],
+ ])('renders nothing for %s', (_name, traceId) => {
+ renderButton({ traceId })
+ expect(screen.queryByText('View trace')).not.toBeInTheDocument()
+ })
+
+ it('renders nothing without tracing access, rather than a disabled button', () => {
+ // Matches how the trace links logs already has behave.
+ window.POSTHOG_APP_CONTEXT = {
+ ...window.POSTHOG_APP_CONTEXT,
+ resource_access_control: { [AccessControlResourceType.Tracing]: AccessControlLevel.None },
+ } as AppContext
+
+ renderButton({ traceId: 'abc123' })
+ expect(screen.queryByText('View trace')).not.toBeInTheDocument()
+ })
+
+ it('links to the trace, anchored on the span and hinted with the timestamp', () => {
+ renderButton({ traceId: 'abc123', spanId: 'def456', timestamp: '2026-06-11T08:00:00.000Z' })
+
+ expect(screen.getByText('View trace').closest('a')).toHaveAttribute(
+ 'href',
+ expect.stringContaining('trace=abc123')
+ )
+ // The timestamp bounds the cold-load query; without it the lookup scans the whole
+ // retention window, because OTel trace ids embed no time.
+ expect(screen.getByText('View trace').closest('a')?.getAttribute('href')).toContain('ts=')
+ })
+})
diff --git a/products/tracing/frontend/components/ViewTraceButton.tsx b/products/tracing/frontend/components/ViewTraceButton.tsx
new file mode 100644
index 000000000000..763e62289cea
--- /dev/null
+++ b/products/tracing/frontend/components/ViewTraceButton.tsx
@@ -0,0 +1,47 @@
+import { IconGraph } from '@posthog/icons'
+import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'
+
+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import { traceUrl } from 'products/tracing/frontend/traceLinks'
+
+export interface ViewTraceButtonProps extends Pick<LemonButtonProps, 'size' | 'type' | 'className' | 'data-attr'> {
+ /** Hex trace id, as every product's query runner returns it. */
+ traceId: string | null | undefined
+ /** Anchors the waterfall on one span. */
+ spanId?: string | null
+ /** Bounds the cold-load lookup — OTel trace ids embed no timestamp. */
+ timestamp?: string | null
+ iconOnly?: boolean
+}
+
+/**
+ * The shared "go to this trace" entry point, for anything that carries a trace id: a log row, an
+ * error event, a metric sample. Mirrors logs' `ViewLogsButton`.
+ */
+export function ViewTraceButton({
+ traceId,
+ spanId,
+ timestamp,
+ iconOnly,
+ ...buttonProps
+}: ViewTraceButtonProps): JSX.Element | null {
+ // Most rows have no trace. Rendering a link to nothing is worse than rendering nothing.
+ // Hidden rather than disabled without access, matching the trace links logs already has.
+ if (!traceId || getAccessControlDisabledReason(AccessControlResourceType.Tracing, AccessControlLevel.Viewer)) {
+ return null
+ }
+
+ return (
+ <LemonButton
+ icon={<IconGraph />}
+ to={traceUrl({ traceId, spanId, ts: timestamp })}
+ tooltip={iconOnly ? 'View the trace this came from' : undefined}
+ {...buttonProps}
+ >
+ {iconOnly ? undefined : 'View trace'}
+ </LemonButton>
+ )
+}