: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
fix(logs): use each team's message keys when deriving patterns (#114450)
Jon McCallum08136a54ceef
diff --git a/docs/published/docs/logs/logs-config.mdx b/docs/published/docs/logs/logs-config.mdxindex de9cadaf2d10..31af13b22f94 100644--- a/docs/published/docs/logs/logs-config.mdx+++ b/docs/published/docs/logs/logs-config.mdx@@ -46,7 +46,7 @@ JSON keys whose value is the message text that log patterns are derived from. DeIn **Settings > Project > Logs > Pattern message extraction**, add or remove keys, drag them into priority order, and select **Save**. Project admins can edit this setting. Clear all keys and save to turn message extraction off.-When a log body is a JSON object, PostHog looks up these keys in order and uses the first one whose value is a non-empty string as the text to build the pattern from. A key whose value is a number, an object, or an empty string is skipped, and the search continues down the list.+When a log body is a JSON object, PostHog looks up these keys in order and uses the first one whose value is a string as the text to build the pattern from. A key whose value is a number or an object is skipped, and the search continues down the list. A key whose value is an empty string still counts as a match, so those logs share an empty pattern.If no key matches, the pattern is built from the object's set of top-level key names instead, so records with the same shape group together.diff --git a/nodejs/src/logs/log-pattern-stage.test.ts b/nodejs/src/logs/log-pattern-stage.test.tsindex 23ced2a86860..a485636c62ae 100644--- a/nodejs/src/logs/log-pattern-stage.test.ts+++ b/nodejs/src/logs/log-pattern-stage.test.ts@@ -1,6 +1,6 @@import type { Counter } from 'prom-client'-import { PATTERN_CAPS, PATTERN_VERSION } from './log-pattern-mask'+import { MESSAGE_KEYS, PATTERN_CAPS, PATTERN_VERSION } from './log-pattern-mask'import {logsPatternBodyKindCounter,logsPatternInputCappedCounter,@@ -41,7 +41,7 @@ describe('log-pattern-stage', () => {}it('tallies body kinds, rule fires, and input caps across a batch without touching the body', async () => {- const stage = makePatternMaskingStage()+ const stage = makePatternMaskingStage(MESSAGE_KEYS)const records = [makeRecord(null),makeRecord('plain 5'),@@ -71,7 +71,7 @@ describe('log-pattern-stage', () => {['a plain body', 'retry 5', 'retry <N>'],['an empty body, which must still carry a version or it reads as written before masking', null, ''],])('stamps pattern and version onto the record: %s', async (_name, body, expected) => {- const stage = makePatternMaskingStage()+ const stage = makePatternMaskingStage(MESSAGE_KEYS)const record = makeRecord(body)await stage.run([record])@@ -80,7 +80,7 @@ describe('log-pattern-stage', () => {})it('keeps the batch when masking throws, so a measurement fault cannot DLQ customer logs', async () => {- const stage = makePatternMaskingStage()+ const stage = makePatternMaskingStage(MESSAGE_KEYS)const record = makeRecord(null)Object.defineProperty(record, 'body', {get: () => {diff --git a/nodejs/src/logs/log-pattern-stage.ts b/nodejs/src/logs/log-pattern-stage.tsindex 4b8ef82c2a9f..5a1231e6806f 100644--- a/nodejs/src/logs/log-pattern-stage.ts+++ b/nodejs/src/logs/log-pattern-stage.ts@@ -1,7 +1,7 @@import { performance } from 'node:perf_hooks'import { Counter, Histogram } from 'prom-client'-import { MASK_RULES, MESSAGE_KEYS, PATTERN_VERSION, buildLogPattern, zeroRuleFires } from './log-pattern-mask'+import { MASK_RULES, PATTERN_VERSION, buildLogPattern, zeroRuleFires } from './log-pattern-mask'import type { LogRecord } from './log-record-avro'import type { MutateStage } from './pipeline/log-processing-pipeline'@@ -51,13 +51,13 @@ export const logsPatternStageErrorCounter = new Counter({help: 'Batches where the pattern masking stage threw. The records survive. Any record the throw came before keeps its stamp, and the rest stay unstamped, which reads as version 0.',})-export function makePatternMaskingStage(): MutateStage {+export function makePatternMaskingStage(messageKeys: readonly string[]): MutateStage {return {kind: 'mutate',name: 'pattern_masking',run: (records) => {try {- stampBatch(records)+ stampBatch(records, messageKeys)} catch {logsPatternStageErrorCounter.inc()}@@ -65,14 +65,14 @@ export function makePatternMaskingStage(): MutateStage {}}-function stampBatch(records: LogRecord[]): void {+function stampBatch(records: LogRecord[], messageKeys: readonly string[]): void {const kindCounts = new Map<string, number>()const ruleFires: number[] = zeroRuleFires()let inputCapped = 0for (const record of records) {const start = performance.now()- const result = buildLogPattern(record.body, MESSAGE_KEYS)+ const result = buildLogPattern(record.body, messageKeys)record.pattern = result.patternrecord.pattern_version = PATTERN_VERSIONlogsPatternMaskingDurationHistogram.observe((performance.now() - start) / 1000)diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.tsindex 9cba41528b6b..2065524d9420 100644--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts@@ -52,6 +52,7 @@ import { compileMetricRules } from './metrics-rules/compile-metric-rules'import type { MetricRulesCache } from './metrics-rules/metric-rules-cache'import type { LogsMetricsEmitter } from './metrics-rules/metrics-emitter'import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT, LogsDlqOutput, LogsOutput } from './outputs/outputs'+import type { PatternMessageKeysCache } from './pattern-message-keys-cache'import { DEFAULT_TRACES_RETENTION_DAYS } from './retention/tracing-config-cache'import { compileRuleSet } from './sampling/compile-rules'import type { SamplingRulesCache } from './sampling/sampling-rules-cache'@@ -116,6 +117,8 @@ const createKafkaMessage = async ({ name: 'instrumentation_scope', type: ['null', 'string'] },{ name: 'event_name', type: ['null', 'string'] },{ name: 'attributes', type: ['null', { type: 'map', values: 'string' }] },+ { name: 'pattern', type: ['null', 'string'], default: null },+ { name: 'pattern_version', type: ['null', 'int'], default: null },],})@@ -215,7 +218,11 @@ describe('LogsIngestionConsumer', () => {depsPartial: Partial<Pick<LogsIngestionConsumerDeps,- 'samplingRulesCache' | 'metricRulesCache' | 'metricsEmitter' | 'logsTransformer'+ | 'samplingRulesCache'+ | 'metricRulesCache'+ | 'metricsEmitter'+ | 'logsTransformer'+ | 'patternMessageKeysCache'>> = {}) => {@@ -2676,5 +2683,27 @@ describe('LogsIngestionConsumer', () => {expect(bodyKindIncSpy).not.toHaveBeenCalled()}})++ it("derives the pattern from the team's message keys, not the defaults", async () => {+ const patternMessageKeysCache = {+ getMessageKeys: jest.fn().mockResolvedValue(['log']),+ } as unknown as PatternMessageKeysCache+ maskingConsumer = await createLogsIngestionConsumer(+ hub,+ { LOGS_PATTERN_MASKING_ENABLED_TEAMS: '*' },+ { patternMessageKeysCache }+ )+ const messages = await createKafkaMessages(+ [createLogMessage({ message: 'default key wins', log: 'team key wins' })],+ {+ token: team.api_token,+ }+ )+ await waitForBackgroundTasks(maskingConsumer.processKafkaBatch(messages))++ const logsMessages = getProducedKafkaMessages().filter((m) => m.topic === 'clickhouse_logs_test')+ const [, , records] = await decodeLogRecords(logsMessages[0].value as Buffer)+ expect(records.map((r) => r.pattern)).toEqual(['team key wins'])+ })})})diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.tsindex 9ce4c164ba54..2a93d131a17f 100644--- a/nodejs/src/logs/logs-ingestion-consumer.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.ts@@ -29,6 +29,7 @@ import {recordLogsDropped,recordLogsReceived,} from './ingestion-otel-metrics'+import { MESSAGE_KEYS } from './log-pattern-mask'import { logsPatternForcedDecodeCounter, makePatternMaskingStage } from './log-pattern-stage'import { type PiiScrubStats } from './log-pii-scrub'import {@@ -44,6 +45,7 @@ import { LogsMetricsEmitter } from './metrics-rules/metrics-emitter'import { buildMetricRulesOtlpPayload } from './metrics-rules/otlp-payload'import { type BatchTallies, createBatchTallies, tallyRecords } from './metrics-rules/tally'import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT, LogsDlqOutput, LogsOutput } from './outputs/outputs'+import { PatternMessageKeysCache } from './pattern-message-keys-cache'import { EMPTY_STAGE_DROP_STATS, type PipelineStage } from './pipeline/log-processing-pipeline'import type { RetentionRuleSource } from './retention/compile-retention-rules'import type { CompiledRetentionRuleSet } from './retention/evaluate-retention'@@ -74,6 +76,8 @@ export interface LogsIngestionConsumerDeps {logsTransformer?: LogsTransformerService/** When set, enabled teams stamp per-row retention from retention rules before produce. */retentionRulesCache?: RetentionRulesCache+ /** When set, pattern masking reads each team's message keys instead of the defaults. */+ patternMessageKeysCache?: PatternMessageKeysCache/*** Resolved outputs registry — must include `LOGS_OUTPUT`, `LOGS_DLQ_OUTPUT`,* and `APP_METRICS_OUTPUT`. The producer + topic for each is wired by the@@ -381,7 +385,6 @@ export class LogsIngestionConsumer {private readonly patternMaskingEnabledTeamsRaw: stringprivate readonly jsonAttributeParsingEnabledTeamsRaw: stringprivate readonly jsonAttributeExtractionEnabledTeamsRaw: string- private readonly patternMaskingStage: PipelineStageprotected groupId: stringprotected topic: string@@ -435,7 +438,6 @@ export class LogsIngestionConsumer {this.patternMaskingEnabledTeamsRaw = mergedConfig.LOGS_PATTERN_MASKING_ENABLED_TEAMSthis.jsonAttributeParsingEnabledTeamsRaw = mergedConfig.LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMSthis.jsonAttributeExtractionEnabledTeamsRaw = mergedConfig.LOGS_JSON_ATTRIBUTE_EXTRACTION_ENABLED_TEAMS- this.patternMaskingStage = makePatternMaskingStage()}private isSamplingEvalEnabledForTeam(teamId: number): boolean {@@ -594,7 +596,11 @@ export class LogsIngestionConsumer {if (modeWithoutMasking !== 'decode_and_reencode') {logsPatternForcedDecodeCounter.inc({ from: modeWithoutMasking })}- stages.push(this.patternMaskingStage)+ const keysCache = this.deps.patternMessageKeysCache+ const messageKeys = keysCache+ ? await this.retryOnDependencyUnavailable(() => keysCache.getMessageKeys(message.teamId))+ : MESSAGE_KEYS+ stages.push(makePatternMaskingStage(messageKeys))}trace.getActiveSpan()?.setAttributes({diff --git a/nodejs/src/logs/pattern-message-keys-cache.test.ts b/nodejs/src/logs/pattern-message-keys-cache.test.tsnew file mode 100644index 000000000000..9b79cb14e345--- /dev/null+++ b/nodejs/src/logs/pattern-message-keys-cache.test.ts@@ -0,0 +1,68 @@+import { DependencyUnavailableError } from '~/common/utils/db/error'+import { PostgresRouter } from '~/common/utils/db/postgres'++import { MESSAGE_KEYS } from './log-pattern-mask'+import { PatternMessageKeysCache } from './pattern-message-keys-cache'++describe('PatternMessageKeysCache', () => {+ let query: jest.Mock+ let cache: PatternMessageKeysCache++ beforeEach(() => {+ query = jest.fn()+ cache = new PatternMessageKeysCache({ query } as unknown as PostgresRouter)+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it.each([+ ["the team's keys in order", [{ logs_pattern_message_keys: ['log', 'message'] }], ['log', 'message']],+ ['an empty list, so extraction stays off', [{ logs_pattern_message_keys: [] }], []],+ ['the defaults when the team has no config row', [], MESSAGE_KEYS],+ ])('serves %s', async (_, rows, expected) => {+ query.mockResolvedValueOnce({ rows })+ expect(await cache.getMessageKeys(1)).toEqual(expected)+ })++ it('serves cached keys inside the refresh window and picks up saved keys after it', async () => {+ const start = Date.now()+ const now = jest.spyOn(Date, 'now').mockReturnValue(start)+ query.mockResolvedValueOnce({ rows: [{ logs_pattern_message_keys: ['log'] }] })+ expect(await cache.getMessageKeys(1)).toEqual(['log'])++ now.mockReturnValue(start + 29_000)+ expect(await cache.getMessageKeys(1)).toEqual(['log'])+ expect(query).toHaveBeenCalledTimes(1)++ now.mockReturnValue(start + 31_000)+ query.mockResolvedValueOnce({ rows: [{ logs_pattern_message_keys: ['msg'] }] })+ expect(await cache.getMessageKeys(1)).toEqual(['msg'])+ expect(query).toHaveBeenCalledTimes(2)+ })++ it('rethrows a dependency outage when nothing is cached', async () => {+ query.mockRejectedValueOnce(new DependencyUnavailableError('pg down', 'Postgres', new Error('pg down')))+ await expect(cache.getMessageKeys(1)).rejects.toBeInstanceOf(DependencyUnavailableError)+ })++ it('serves the last-known keys after a failed refresh, and waits before querying again', async () => {+ const start = Date.now()+ const now = jest.spyOn(Date, 'now').mockReturnValue(start)+ query.mockResolvedValueOnce({ rows: [{ logs_pattern_message_keys: [] }] })+ await cache.getMessageKeys(1)++ now.mockReturnValue(start + 60_000)+ query.mockRejectedValue(new Error('relation "logs_teamlogsconfig" does not exist'))+ const results = await Promise.all(Array.from({ length: 50 }, () => cache.getMessageKeys(1)))+ expect(results).toEqual(Array(50).fill([]))+ expect(await cache.getMessageKeys(1)).toEqual([])+ expect(query).toHaveBeenCalledTimes(2)++ now.mockReturnValue(start + 66_000)+ query.mockResolvedValueOnce({ rows: [{ logs_pattern_message_keys: ['msg'] }] })+ expect(await cache.getMessageKeys(1)).toEqual(['msg'])+ expect(query).toHaveBeenCalledTimes(3)+ })+})diff --git a/nodejs/src/logs/pattern-message-keys-cache.ts b/nodejs/src/logs/pattern-message-keys-cache.tsnew file mode 100644index 000000000000..e649520d37cf--- /dev/null+++ b/nodejs/src/logs/pattern-message-keys-cache.ts@@ -0,0 +1,95 @@+import { trace } from '@opentelemetry/api'++import { instrumentFn } from '~/common/tracing/tracing-utils'+import { DependencyUnavailableError } from '~/common/utils/db/error'+import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'+import { logger } from '~/common/utils/logger'++import { MESSAGE_KEYS } from './log-pattern-mask'++const REFRESH_MS = 30_000+const FAILED_REFRESH_RETRY_MS = 5_000++type CacheEntry = {+ messageKeys: readonly string[]+ expiresAtMs: number+}++const patternMessageKeysInstrumentOpts = { measureTime: false, sendException: false } as const++export class PatternMessageKeysCache {+ private cache = new Map<number, CacheEntry>()+ private inflight = new Map<number, Promise<readonly string[]>>()++ constructor(private postgres: PostgresRouter) {}++ public async getMessageKeys(teamId: number): Promise<readonly string[]> {+ return instrumentFn(+ {+ key: 'logsIngestion.patterns.getMessageKeys',+ ...patternMessageKeysInstrumentOpts,+ getLoggingContext: () => ({ team_id: teamId }),+ },+ async () => {+ const existing = this.cache.get(teamId)+ if (existing && Date.now() < existing.expiresAtMs) {+ trace.getActiveSpan()?.setAttributes({ 'logs.patterns.message_keys_cache_hit': true })+ return existing.messageKeys+ }++ // Messages are processed concurrently, so share one refresh per team.+ let refresh = this.inflight.get(teamId)+ if (!refresh) {+ refresh = this.refresh(teamId, existing).finally(() => this.inflight.delete(teamId))+ this.inflight.set(teamId, refresh)+ }+ return refresh+ }+ )+ }++ private async refresh(teamId: number, existing: CacheEntry | undefined): Promise<readonly string[]> {+ let messageKeys: readonly string[]+ try {+ messageKeys = await this.fetchMessageKeys(teamId)+ } catch (error) {+ if (!existing && error instanceof DependencyUnavailableError) {+ throw error+ }+ logger.warn('[logs-patterns] message keys fetch failed — falling back', {+ teamId,+ error: String(error),+ })+ trace.getActiveSpan()?.setAttributes({+ 'logs.patterns.message_keys_fetch_failed': true,+ 'logs.patterns.message_keys_served_stale': Boolean(existing),+ })+ const fallback = existing?.messageKeys ?? MESSAGE_KEYS+ // Hold the fallback briefly so a down database is not queried on every message.+ this.cache.set(teamId, { messageKeys: fallback, expiresAtMs: Date.now() + FAILED_REFRESH_RETRY_MS })+ return fallback+ }++ this.cache.set(teamId, { messageKeys, expiresAtMs: Date.now() + REFRESH_MS })+ trace.getActiveSpan()?.setAttributes({+ 'logs.patterns.message_keys_cache_hit': false,+ 'logs.patterns.message_keys_count': messageKeys.length,+ })+ return messageKeys+ }++ private async fetchMessageKeys(teamId: number): Promise<readonly string[]> {+ const res = await this.postgres.query<{ logs_pattern_message_keys: unknown }>(+ PostgresUse.COMMON_READ,+ `SELECT logs_pattern_message_keys FROM logs_teamlogsconfig WHERE team_id = $1`,+ [teamId],+ 'logs-pattern-message-keys-fetch'+ )+ // A team that never opened logs settings has no row yet.+ const stored = res.rows[0]?.logs_pattern_message_keys+ if (!Array.isArray(stored) || !stored.every((key) => typeof key === 'string')) {+ return MESSAGE_KEYS+ }+ return stored+ }+}diff --git a/nodejs/src/servers/ingestion-logs-server.ts b/nodejs/src/servers/ingestion-logs-server.tsindex 74394d5a239d..2f36c279ce3c 100644--- a/nodejs/src/servers/ingestion-logs-server.ts+++ b/nodejs/src/servers/ingestion-logs-server.ts@@ -26,6 +26,7 @@ import {getDefaultKafkaWarpstreamLogsProducerEnvConfig,} from '~/logs/outputs/producers'import { createLogsOutputsRegistry } from '~/logs/outputs/registry'+import { PatternMessageKeysCache } from '~/logs/pattern-message-keys-cache'import { RetentionRulesCache } from '~/logs/retention/retention-rules-cache'import { SamplingRulesCache } from '~/logs/sampling/sampling-rules-cache'import { LogsTransformerService } from '~/logs/transformations/logs-transformer.service'@@ -130,6 +131,7 @@ export class IngestionLogsServer implements NodeServer {? new LogsMetricsEmitter(this.config.LOGS_METRICS_RULES_EXPORT_URL): undefinedconst retentionRulesCache = new RetentionRulesCache(this.postgres)+ const patternMessageKeysCache = new PatternMessageKeysCache(this.postgres)// 2. Resolve outputs (topic + producer per logical name, env-controlled)const outputs = createLogsOutputsRegistry().build(this.producerRegistry, this.config)@@ -170,6 +172,7 @@ export class IngestionLogsServer implements NodeServer {metricsEmitter,logsTransformer,retentionRulesCache,+ patternMessageKeysCache,usageBatch,})await consumer.start()