: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): mirror visible log rows as a window on the sparkline (#60672)
Jon McCallumeb689518e275
diff --git a/frontend/src/lib/components/Sparkline.tsx b/frontend/src/lib/components/Sparkline.tsxindex e1f5a58c13da..73dd8987773d 100644--- a/frontend/src/lib/components/Sparkline.tsx+++ b/frontend/src/lib/components/Sparkline.tsx@@ -9,7 +9,7 @@ import { getColorVar } from 'lib/colors'import { useChart } from 'lib/hooks/useChart'import { useEventListener } from 'lib/hooks/useEventListener'import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'-import { humanFriendlyNumber } from 'lib/utils'+import { hexToRGBA, humanFriendlyNumber } from 'lib/utils'import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'import { LemonSkeleton } from '../lemon-ui/LemonSkeleton'@@ -74,6 +74,13 @@ export interface SparklineProps {referenceLines?: SparklineReferenceLine[]/** Format the per-series tooltip value. Defaults to `humanFriendlyNumber`. */renderTooltipValue?: (value: number) => string+ /**+ * Inclusive label-index range to highlight as a translucent box behind the bars.+ * Used to mirror an external selection (e.g. the rows currently visible in a+ * paired virtualized list) onto the chart. Out-of-range or inverted ranges are+ * clamped; pass `null`/`undefined` to clear.+ */+ highlightedRange?: { startIndex: number; endIndex: number } | null}export function Sparkline({@@ -96,6 +103,7 @@ export function Sparkline({sortTooltipByCount = false,referenceLines,renderTooltipValue,+ highlightedRange,}: SparklineProps): JSX.Element {const tooltipRef = useRef<HTMLDivElement | null>(null)@@ -242,43 +250,69 @@ export function Sparkline({setTooltip({ ...tooltip } as TooltipModel<'bar'>)},},- ...(referenceLines && referenceLines.length > 0- ? {- annotation: {- annotations: Object.fromEntries(- referenceLines.map((line, i) => {- const lineColor = getColorVar(line.color || 'danger')- return [- `referenceLine${i}`,- {- type: 'line',- yMin: line.value,- yMax: line.value,- borderColor: lineColor,- borderWidth: 1.5,- borderDash: [5, 4],- ...(line.label- ? {- label: {- display: true,- content: line.label,- position: line.labelPosition || 'end',- font: { size: 9 },- color: lineColor,- backgroundColor: 'transparent',- // Sit the label just above the line so it doesn't render on top of it.- // The 20% y-axis headroom set above guarantees it stays inside the chart.- yAdjust: -8,- },- }- : {}),+ ...(() => {+ const annotations: Record<string, any> = {}++ if (referenceLines && referenceLines.length > 0) {+ referenceLines.forEach((line, i) => {+ const lineColor = getColorVar(line.color || 'danger')+ annotations[`referenceLine${i}`] = {+ type: 'line',+ yMin: line.value,+ yMax: line.value,+ borderColor: lineColor,+ borderWidth: 1.5,+ borderDash: [5, 4],+ ...(line.label+ ? {+ label: {+ display: true,+ content: line.label,+ position: line.labelPosition || 'end',+ font: { size: 9 },+ color: lineColor,+ backgroundColor: 'transparent',+ // Sit the label just above the line so it doesn't render on top of it.+ // The 20% y-axis headroom set above guarantees it stays inside the chart.+ yAdjust: -8,},- ]- })- ),- },- }- : {}),+ }+ : {}),+ }+ })+ }++ if (highlightedRange && labels && labels.length > 0) {+ const lastIdx = labels.length - 1+ const lo = Math.max(0, Math.min(highlightedRange.startIndex, highlightedRange.endIndex))+ const hi = Math.min(+ lastIdx,+ Math.max(highlightedRange.startIndex, highlightedRange.endIndex)+ )+ if (lo <= hi) {+ // Match the cursor-row highlight hue (`--primary-highlight`):+ // orange in light mode, amber in dark. Read the concrete+ // per-theme token since the semantic var is a nested `var()`+ // that doesn't resolve off-DOM (e.g. on the chart canvas).+ const isDark = document.body.getAttribute('theme') === 'dark'+ const primary = getColorVar(isDark ? 'primary-3000-dark' : 'primary-3000-light')+ annotations.highlightedRange = {+ type: 'box',+ xMin: labels[lo],+ // Extend to the next bucket's start so the last bar is fully enclosed.+ xMax: labels[hi + 1] ?? labels[hi],+ // Drawn under the bars so the data stays legible.+ drawTime: 'beforeDatasetsDraw',+ // 10% fill mirrors the cursor row; a stronger border marks the window edges.+ backgroundColor: hexToRGBA(primary, 0.1),+ borderColor: hexToRGBA(primary, 0.8),+ borderWidth: 1,+ }+ }+ }++ return Object.keys(annotations).length > 0 ? { annotation: { annotations } } : {}+ })(),},maintainAspectRatio: false,interaction: {@@ -289,7 +323,18 @@ export function Sparkline({},}},- deps: [labels, adjustedData, withXScale, withYScale, renderLabel, data, maximumIndicator, type, referenceLines],+ deps: [+ labels,+ adjustedData,+ withXScale,+ withYScale,+ renderLabel,+ data,+ maximumIndicator,+ type,+ referenceLines,+ highlightedRange,+ ],})const dataPointCount = adjustedData[0]?.values?.length || 0diff --git a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsxindex 926878f6fdc5..e6d271dc88a4 100644--- a/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx+++ b/products/logs/frontend/components/LogsViewer/LogsViewerSparkline/index.tsx@@ -1,3 +1,4 @@+import { useValues } from 'kea'import { useCallback, useMemo } from 'react'import { IconChevronDown } from '@posthog/icons'@@ -11,6 +12,8 @@ import { cn } from 'lib/utils/css-classes'import { DateRange, LogsSparklineBreakdownBy } from '~/queries/schema/schema-general'+import { logsViewerLogic } from 'products/logs/frontend/components/LogsViewer/logsViewerLogic'+export interface LogsSparklineData {data: {color: string | undefined@@ -106,6 +109,40 @@ export function LogsSparkline({return sparklineData.dates.map((date) => dayjs(date).toISOString())}, [sparklineData.dates])+ const { visibleRowDateRange } = useValues(logsViewerLogic)++ // Map the visible-row date range onto bucket indices in `dates`. Buckets are+ // anchored at their start time; the date_to range edge belongs to the bucket+ // whose start is the last one <= date_to.+ const highlightedRange = useMemo(() => {+ if (!visibleRowDateRange || sparklineData.dates.length === 0) {+ return null+ }+ const fromMs = dayjs(visibleRowDateRange.date_from).valueOf()+ const toMs = dayjs(visibleRowDateRange.date_to).valueOf()+ let startIndex = -1+ let endIndex = -1+ for (let i = 0; i < sparklineData.dates.length; i++) {+ const bucketMs = dayjs(sparklineData.dates[i]).valueOf()+ if (bucketMs <= fromMs) {+ startIndex = i+ }+ if (bucketMs <= toMs) {+ endIndex = i+ } else {+ break+ }+ }+ // Fall back to the first bucket when the range starts before any bucket.+ if (startIndex === -1) {+ startIndex = 0+ }+ if (endIndex === -1 || endIndex < startIndex) {+ return null+ }+ return { startIndex, endIndex }+ }, [visibleRowDateRange, sparklineData.dates])+const onSelectionChange = useCallback((selection: { startIndex: number; endIndex: number }): void => {const dates = sparklineData.dates@@ -159,6 +196,7 @@ export function LogsSparkline({tooltipRowCutoff={100}hideZerosInTooltipsortTooltipByCount+ highlightedRange={highlightedRange}/>) : !sparklineLoading ? (<div className="h-full text-muted flex items-center justify-center">diff --git a/products/logs/frontend/components/LogsViewer/logsViewerLogic.test.ts b/products/logs/frontend/components/LogsViewer/logsViewerLogic.test.tsindex d0cd7133c6b5..1a6cf2111c78 100644--- a/products/logs/frontend/components/LogsViewer/logsViewerLogic.test.ts+++ b/products/logs/frontend/components/LogsViewer/logsViewerLogic.test.ts@@ -781,4 +781,71 @@ describe('logsViewerLogic', () => {expect(logic.values.prettifiedLogIds.size).toBe(0)})})++ describe('visible row range tracking', () => {+ const rawLogsWithTimestamps: LogMessage[] = [+ { ...createMockRawLog('log-1'), timestamp: '2024-01-01T00:00:00Z' },+ { ...createMockRawLog('log-2'), timestamp: '2024-01-01T01:00:00Z' },+ { ...createMockRawLog('log-3'), timestamp: '2024-01-01T02:00:00Z' },+ { ...createMockRawLog('log-4'), timestamp: '2024-01-01T03:00:00Z' },+ ]++ beforeEach(() => {+ ;({ logic } = mountWithLogs(rawLogsWithTimestamps))+ })++ it('defaults to null', () => {+ expect(logic.values.visibleRowRange).toBeNull()+ expect(logic.values.visibleRowDateRange).toBeNull()+ })++ it('records the visible row index range', () => {+ logic.actions.setVisibleRowRange(1, 2)+ expect(logic.values.visibleRowRange).toEqual({ startIndex: 1, stopIndex: 2 })+ })++ it.each([+ {+ name: 'ascending logs',+ reverseLogs: false,+ range: [1, 2] as const,+ expected: { date_from: '2024-01-01T01:00:00.000Z', date_to: '2024-01-01T02:00:00.000Z' },+ },+ {+ // "Latest first" — startIndex points at a later timestamp than stopIndex.+ name: 'descending logs',+ reverseLogs: true,+ range: [0, 1] as const,+ expected: { date_from: '2024-01-01T02:00:00.000Z', date_to: '2024-01-01T03:00:00.000Z' },+ },+ {+ name: 'single-row range',+ reverseLogs: false,+ range: [2, 2] as const,+ expected: { date_from: '2024-01-01T02:00:00.000Z', date_to: '2024-01-01T02:00:00.000Z' },+ },+ ])('derives a date range ordered earliest-first ($name)', ({ reverseLogs, range, expected }) => {+ if (reverseLogs) {+ logic.actions.setLogs([...rawLogsWithTimestamps].reverse())+ }+ logic.actions.setVisibleRowRange(range[0], range[1])+ expect(logic.values.visibleRowDateRange).toEqual(expected)+ })++ it('clamps indices that fall outside the loaded logs', () => {+ logic.actions.setVisibleRowRange(0, 999)+ expect(logic.values.visibleRowDateRange).toEqual({+ date_from: '2024-01-01T00:00:00.000Z',+ date_to: '2024-01-01T03:00:00.000Z',+ })+ })++ it('clears when logs are replaced', () => {+ logic.actions.setVisibleRowRange(0, 2)+ expect(logic.values.visibleRowRange).not.toBeNull()+ logic.actions.setLogs([createMockRawLog('new-log')])+ expect(logic.values.visibleRowRange).toBeNull()+ expect(logic.values.visibleRowDateRange).toBeNull()+ })+ })})diff --git a/products/logs/frontend/components/LogsViewer/logsViewerLogic.ts b/products/logs/frontend/components/LogsViewer/logsViewerLogic.tsindex fbc987d0e82f..d86f99c3e6d6 100644--- a/products/logs/frontend/components/LogsViewer/logsViewerLogic.ts+++ b/products/logs/frontend/components/LogsViewer/logsViewerLogic.ts@@ -27,6 +27,11 @@ export interface VisibleLogsTimeRange {date_to: string}+export interface VisibleRowRange {+ startIndex: number+ stopIndex: number+}+export type LogCursor = number | nullexport interface LogsViewerLogicProps {@@ -134,6 +139,10 @@ export const logsViewerLogic = kea<logsViewerLogicType>([// Per-row prettifytogglePrettifyLog: (logId: string) => ({ logId }),++ // Scroll position in the virtualized list (the range of rows currently in+ // the viewport). Drives the brush overlay on the sparkline.+ setVisibleRowRange: (startIndex: number, stopIndex: number) => ({ startIndex, stopIndex }),}),reducers(() => ({@@ -308,6 +317,15 @@ export const logsViewerLogic = kea<logsViewerLogicType>([setLogs: () => new Set<string>(),},],++ visibleRowRange: [+ null as VisibleRowRange | null,+ {+ setVisibleRowRange: (_, { startIndex, stopIndex }) => ({ startIndex, stopIndex }),+ clearLogs: () => null,+ setLogs: () => null,+ },+ ],})),selectors({@@ -352,6 +370,33 @@ export const logsViewerLogic = kea<logsViewerLogicType>([},],+ // Date range covered by the currently-visible (scrolled-into-view) rows.+ // Returns null when no rows are rendered or the indices don't line up with+ // loaded logs. The values are always ordered date_from <= date_to regardless+ // of `orderBy`.+ visibleRowDateRange: [+ (state) => [state.visibleRowRange, state.logs],+ (visibleRowRange: VisibleRowRange | null, logs: ParsedLogMessage[]): VisibleLogsTimeRange | null => {+ if (!visibleRowRange || logs.length === 0) {+ return null+ }+ const startIndex = Math.max(0, Math.min(visibleRowRange.startIndex, logs.length - 1))+ const stopIndex = Math.max(0, Math.min(visibleRowRange.stopIndex, logs.length - 1))+ const a = logs[startIndex]?.timestamp+ const b = logs[stopIndex]?.timestamp+ if (!a || !b) {+ return null+ }+ const ta = dayjs(a)+ const tb = dayjs(b)+ const [earlier, later] = ta.isBefore(tb) ? [ta, tb] : [tb, ta]+ return {+ date_from: earlier.toISOString(),+ date_to: later.toISOString(),+ }+ },+ ],+logsCount: [(s) => [s.logs], (logs: ParsedLogMessage[]): number => logs.length],// Derived: ordered array of attribute column keysdiff --git a/products/logs/frontend/components/VirtualizedLogsList/VirtualizedLogsList.tsx b/products/logs/frontend/components/VirtualizedLogsList/VirtualizedLogsList.tsxindex 9678a39baa2c..b7fb63920af4 100644--- a/products/logs/frontend/components/VirtualizedLogsList/VirtualizedLogsList.tsx+++ b/products/logs/frontend/components/VirtualizedLogsList/VirtualizedLogsList.tsx@@ -167,6 +167,7 @@ export function VirtualizedLogsList({selectLogRange,togglePrettifyLog,setFocused,+ setVisibleRowRange,} = useActions(logsViewerLogic)const { openLogDetails } = useActions(logDetailsModalLogic)@@ -242,9 +243,13 @@ export function VirtualizedLogsList({}}, [disableCursor, scrollToCursorRequest, cursorIndex, listRef])+ // Tracks the last range we dispatched so we don't fire setVisibleRowRange on+ // every overscan tick when nothing actually changed.+ const lastVisibleRangeRef = useRef<{ startIndex: number; stopIndex: number } | null>(null)+const handleRowsRendered = useCallback((- _visibleRows: { startIndex: number; stopIndex: number },+ visibleRows: { startIndex: number; stopIndex: number },allRows: { startIndex: number; stopIndex: number }): void => {if (@@ -253,8 +258,22 @@ export function VirtualizedLogsList({) {onLoadMore?.()}++ const prev = lastVisibleRangeRef.current+ if (!prev || prev.startIndex !== visibleRows.startIndex || prev.stopIndex !== visibleRows.stopIndex) {+ lastVisibleRangeRef.current = { startIndex: visibleRows.startIndex, stopIndex: visibleRows.stopIndex }+ setVisibleRowRange(visibleRows.startIndex, visibleRows.stopIndex)+ }},- [disableInfiniteScroll, shouldLoadMore, dataSource.length, hasMoreLogsToLoad, loading, onLoadMore]+ [+ disableInfiniteScroll,+ shouldLoadMore,+ dataSource.length,+ hasMoreLogsToLoad,+ loading,+ onLoadMore,+ setVisibleRowRange,+ ])const handleLogRowClick = useCallback(