: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): wire facets to cross-filtered counts endpoint (#64809)
Jon McCallumf8f37ea01363
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsxindex f235457b63c5..b95fc42cfb26 100644--- a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx+++ b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx@@ -7,12 +7,12 @@ import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLimport { LogSeverityLevel } from '~/queries/schema/schema-general'import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'-import { logsViewerDataLogic } from 'products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'import { serviceFilterLogic } from 'products/logs/frontend/components/LogsViewer/Filters/serviceFilterLogic'import { SEVERITY_BAR_COLORS } from 'products/logs/frontend/components/VirtualizedLogsList/columnDefinitions'import { Facet, FacetOption } from './Facet'+import { facetCountsLogic } from './facetCountsLogic'import { facetRailLogic } from './facetRailLogic'const DEFAULT_WIDTH_PX = 240@@ -39,11 +39,11 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {const railRef = useRef<HTMLDivElement>(null)const { setFacetRailCollapsed } = useActions(logsViewerConfigLogic)const { severityLevels, serviceNames, utcDateRange } = useValues(logsViewerFiltersLogic)- const { severityTotals } = useValues(logsViewerDataLogic)+ const { levelCounts, serviceCounts } = useValues(facetCountsLogic({ id }))const { collapsedFacets } = useValues(facetRailLogic({ id }))const { toggleSeverityLevel, toggleServiceName, toggleFacetCollapsed } = useActions(facetRailLogic({ id }))- const levelOptions = SEVERITY_OPTIONS.map((option) => ({ ...option, count: severityTotals?.[option.value] }))+ const levelOptions = SEVERITY_OPTIONS.map((option) => ({ ...option, count: levelCounts[option.value] }))const onToggleClosed = useCallback((shouldBeClosed: boolean) => setFacetRailCollapsed(shouldBeClosed),@@ -90,6 +90,7 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {<ServiceFacetselected={serviceNames ?? []}onToggle={toggleServiceName}+ counts={serviceCounts}collapsed={collapsedFacets.includes('service')}onToggleCollapsed={() => toggleFacetCollapsed('service')}/>@@ -103,18 +104,20 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {function ServiceFacet({selected,onToggle,+ counts,collapsed,onToggleCollapsed,}: {selected: string[]onToggle: (name: string) => void+ counts: Record<string, number>collapsed: booleanonToggleCollapsed: () => void}): JSX.Element {- const { serviceValues, allServiceNamesLoading, search } = useValues(serviceFilterLogic)+ const { serviceNames, allServiceNamesLoading, search } = useValues(serviceFilterLogic)const { setSearch } = useActions(serviceFilterLogic)- const options: FacetOption[] = serviceValues.map((s) => ({ value: s.name, label: s.name, count: s.count }))+ const options: FacetOption[] = serviceNames.map((name) => ({ value: name, label: name, count: counts[name] }))return (<Facetdiff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.tsnew file mode 100644index 000000000000..2eb6f0a7aa7f--- /dev/null+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts@@ -0,0 +1,105 @@+import { connect, kea, key, path, props } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import { teamLogic } from 'scenes/teamLogic'++import { UniversalFiltersGroup } from '~/types'++import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'++import { logsFacetValuesCreate } from '../../../generated/api'+import { _LogFacetValueApi, _LogPropertyFilterApi } from '../../../generated/api.schemas'+import type { facetCountsLogicType } from './facetCountsLogicType'++export interface FacetCountsLogicProps {+ id: string+}++type FacetField = 'severity_text' | 'service_name'++function toCountMap(results: _LogFacetValueApi[]): Record<string, number> {+ return Object.fromEntries(results.map((r) => [r.value, r.count]))+}++/**+ * Per-facet value counts, cross-filtered server-side: each facet's counts reflect every active+ * filter except its own selection. Refetches whenever the filters change.+ */+export const facetCountsLogic = kea<facetCountsLogicType>([+ props({ id: 'default' } as FacetCountsLogicProps),+ key((props) => props.id),+ path((key) => ['products', 'logs', 'frontend', 'components', 'LogsViewer', 'FacetRail', 'facetCountsLogic', key]),++ connect((props: FacetCountsLogicProps) => ({+ values: [+ logsViewerFiltersLogic({ id: props.id }),+ ['filters', 'utcDateRange', 'queryFilterGroup'],+ teamLogic,+ ['currentTeamId'],+ ],+ })),++ loaders(({ values }) => {+ const fetchCounts = async (facetField: FacetField): Promise<Record<string, number>> => {+ if (!values.currentTeamId) {+ return {}+ }+ const group = values.queryFilterGroup as UniversalFiltersGroup+ const filterGroup = ((group?.values?.[0] as UniversalFiltersGroup | undefined)?.values ??+ []) as unknown as _LogPropertyFilterApi[]+ const response = await logsFacetValuesCreate(String(values.currentTeamId), {+ query: {+ facetField,+ dateRange: values.utcDateRange,+ severityLevels: values.filters.severityLevels ?? [],+ serviceNames: values.filters.serviceNames ?? [],+ searchTerm: values.filters.searchTerm || undefined,+ filterGroup,+ },+ })+ return toCountMap(response.results)+ }++ return {+ levelCounts: [+ {} as Record<string, number>,+ {+ loadLevelCounts: async (_: null, breakpoint) => {+ await breakpoint(300)+ const counts = await fetchCounts('severity_text')+ breakpoint()+ return counts+ },+ },+ ],+ serviceCounts: [+ {} as Record<string, number>,+ {+ loadServiceCounts: async (_: null, breakpoint) => {+ await breakpoint(300)+ const counts = await fetchCounts('service_name')+ breakpoint()+ return counts+ },+ },+ ],+ }+ }),++ subscriptions(({ actions }) => {+ // Fires on mount (initial load) and on any change. We watch both `filters` (severity,+ // service, search, date, user filterGroup) and `queryFilterGroup` (which folds in+ // pinnedFilters, e.g. the person-tab distinct_id pin) so counts re-fetch when the pinned+ // scope changes too. `filterGroup` feeds both, so a normal edit fires both — the 300ms+ // debounce in each loader collapses that into one request.+ const reload = (): void => {+ actions.loadLevelCounts(null)+ actions.loadServiceCounts(null)+ }+ return {+ filters: reload,+ queryFilterGroup: reload,+ }+ }),+])diff --git a/products/logs/frontend/components/LogsViewer/Filters/serviceFilterLogic.ts b/products/logs/frontend/components/LogsViewer/Filters/serviceFilterLogic.tsindex e744f82cfe70..d4629afe9a04 100644--- a/products/logs/frontend/components/LogsViewer/Filters/serviceFilterLogic.ts+++ b/products/logs/frontend/components/LogsViewer/Filters/serviceFilterLogic.ts@@ -13,11 +13,6 @@ export interface ServiceFilterLogicProps {dateRange?: DateRange}-export interface ServiceValue {- name: string- count?: number-}-export const serviceFilterLogic = kea<serviceFilterLogicType>([path(['products', 'logs', 'frontend', 'components', 'LogsViewer', 'Filters', 'serviceFilterLogic']),props({} as ServiceFilterLogicProps),@@ -37,7 +32,7 @@ export const serviceFilterLogic = kea<serviceFilterLogicType>([loaders(({ values, props: logicProps }) => ({allServiceNames: [- [] as ServiceValue[],+ [] as string[],{loadServiceNames: async () => {const url = combineUrl(`api/environments/${values.currentTeamId}/logs/values`, {@@ -49,17 +44,14 @@ export const serviceFilterLogic = kea<serviceFilterLogicType>([}).url// nosemgrep: prefer-codegen-apiconst response = await api.get(url)- return (response.results ?? []) as ServiceValue[]+ return ((response.results ?? []) as { name: string }[]).map((r) => r.name)},},],})),selectors({- // Names only — kept for the legacy ServiceFilter dropdown (flag off).- serviceNames: [(s) => [s.allServiceNames], (allServiceNames): string[] => allServiceNames.map((r) => r.name)],- // Name + count — used by the facet rail to show per-value counts.- serviceValues: [(s) => [s.allServiceNames], (allServiceNames): ServiceValue[] => allServiceNames],+ serviceNames: [(s) => [s.allServiceNames], (allServiceNames): string[] => allServiceNames],}),listeners(({ actions }) => ({diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.tsindex fc847fbcdb0f..a29c16bef59a 100644--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts@@ -481,26 +481,6 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([(s) => [s.sparkline],(sparkline): number => sparkline?.reduce((sum: number, item: any) => sum + item.count, 0) ?? 0,],- // Per-severity totals for the facet rail's Level counts, summed from the already-loaded- // sparkline. Only available when the sparkline is broken down by severity (the default);- // returns null otherwise so the Level facet just omits counts rather than showing wrong ones.- severityTotals: [- (s) => [s.sparkline, s.sparklineBreakdownBy],- (- sparkline: any[] | null,- sparklineBreakdownBy: LogsSparklineBreakdownBy- ): Record<string, number> | null => {- if (!sparkline || sparklineBreakdownBy !== 'severity') {- return null- }- return sparkline.reduce((acc: Record<string, number>, row: any) => {- if (row.severity) {- acc[row.severity] = (acc[row.severity] ?? 0) + row.count- }- return acc- }, {})- },- ],logsRemainingToLoad: [(s) => [s.totalLogsMatchingFilters, s.logs],(totalLogsMatchingFilters, logs): number => totalLogsMatchingFilters - logs.length,