: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 measure-only pattern masking into the logs consumer (#88233)
Jon McCallumc34efc5d6d47
diff --git a/nodejs/src/logs/config.ts b/nodejs/src/logs/config.tsindex b70d1b0feefb..e171302456d1 100644--- a/nodejs/src/logs/config.ts+++ b/nodejs/src/logs/config.ts@@ -68,6 +68,12 @@ export type LogsIngestionConsumerConfig = {LOGS_RETENTION_ENABLED_TEAMS: string/** When `true`, retention rules are never evaluated (rows keep the team default via the batch header). */LOGS_RETENTION_KILLSWITCH: boolean+ /** Comma-separated team IDs, or `*` for all teams, or empty (default) to disable measure-only pattern masking. */+ LOGS_PATTERN_MASKING_ENABLED_TEAMS: string+ /** Ceiling on body chars fed to the pattern masker; longer bodies are cut first (CPU guard). */+ LOGS_PATTERN_MASKING_MAX_INPUT_CHARS: number+ /** Truncation applied to the masked pattern, after masking (so more real content survives the cut). */+ LOGS_PATTERN_MASKING_MAX_OUTPUT_CHARS: number/*** When `true`, rows removed by drop rules are credited back to the billed usage metrics* (`bytes_ingested` / `records_ingested`). When `false` (default), the credit is only@@ -119,6 +125,10 @@ export function getDefaultLogsIngestionConsumerConfig(): LogsIngestionConsumerCo// Off in prod until per-team rollout; on in dev for local end-to-end testing.LOGS_RETENTION_ENABLED_TEAMS: isProdEnv() ? '' : '*',LOGS_RETENTION_KILLSWITCH: false,+ // Off by default: enabling forces decode+re-encode for allowlisted teams.+ LOGS_PATTERN_MASKING_ENABLED_TEAMS: '',+ LOGS_PATTERN_MASKING_MAX_INPUT_CHARS: DEFAULT_PATTERN_MAX_INPUT_CHARS,+ LOGS_PATTERN_MASKING_MAX_OUTPUT_CHARS: DEFAULT_PATTERN_MAX_OUTPUT_CHARS,LOGS_BILLING_PRORATE_ENABLED: false,LOGS_TRANSFORMATIONS_ENABLED_TEAMS: '',LOGS_TRANSFORMATIONS_KILLSWITCH: false,diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.tsindex eeb1f325df9c..da35160c50e9 100644--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts@@ -27,6 +27,7 @@ import { Hub, Team } from '~/types'import { getDefaultTracesIngestionConsumerConfig } from './config'import * as otelMetrics from './ingestion-otel-metrics'import { resetLogsIngestionInstrumentsForTests } from './ingestion-otel-metrics'+import { logsPatternBodyKindCounter } from './log-pattern-stage'import { LogRecord, decodeLogRecords, encodeLogRecords } from './log-record-avro'import {DEFAULT_LOGS_RETENTION_DAYS,@@ -2115,6 +2116,12 @@ describe('LogsIngestionConsumer', () => {return tracesConsumer}+ it('leaves pattern masking off even on a wildcard allowlist, because a trace record has no body', () => {+ const tracesConsumer = createTracesIngestionConsumer({ LOGS_PATTERN_MASKING_ENABLED_TEAMS: '*' })++ expect(tracesConsumer['isPatternMaskingEnabledForTeam'](team.id)).toEqual(false)+ })+it('meters usage as traces, not logs', async () => {const tracesConsumer = createTracesIngestionConsumer()tracesConsumer['queueUsageMetric'](team.id, 'bytes_ingested', 500)@@ -2312,4 +2319,36 @@ describe('LogsIngestionConsumer', () => {expect(logsMessages).toHaveLength(1)})})++ describe('pattern masking (measure-only)', () => {+ let maskingConsumer: LogsIngestionConsumer | undefined++ afterEach(async () => {+ await maskingConsumer?.stop()+ maskingConsumer = undefined+ })++ it.each([+ ['a wildcard allowlist runs the masking stage', () => '*', true],+ ['an empty allowlist does not run the masking stage', () => '', false],+ ["the team's id in the allowlist runs the masking stage", () => String(team.id), true],+ ["only another team's id in the allowlist does not run the masking stage", () => String(team2.id), false],+ ])('%s', async (_name, allowlist, expectMasked) => {+ const bodyKindIncSpy = jest.spyOn(logsPatternBodyKindCounter, 'inc')+ maskingConsumer = await createLogsIngestionConsumer(hub, {+ LOGS_PATTERN_MASKING_ENABLED_TEAMS: allowlist(),+ })++ const messages = await createKafkaMessages([createLogMessage()], { token: team.api_token })+ await waitForBackgroundTasks(maskingConsumer.processKafkaBatch(messages))++ const logsMessages = getProducedKafkaMessages().filter((m) => m.topic === 'clickhouse_logs_test')+ expect(logsMessages).toHaveLength(1)+ if (expectMasked) {+ expect(bodyKindIncSpy).toHaveBeenCalled()+ } else {+ expect(bodyKindIncSpy).not.toHaveBeenCalled()+ }+ })+ })})diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.tsindex baf449c59a33..4013e35ae179 100644--- a/nodejs/src/logs/logs-ingestion-consumer.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.ts@@ -25,8 +25,14 @@ import {recordLogsDropped,recordLogsReceived,} from './ingestion-otel-metrics'+import { logsPatternForcedDecodeCounter, makePatternMaskingStage } from './log-pattern-stage'import { type PiiScrubStats } from './log-pii-scrub'-import { type LogRecord, type LogRecordsTransform, processLogMessageBuffer } from './log-record-avro'+import {+ type LogRecord,+ type LogRecordsTransform,+ bufferProcessingMode,+ processLogMessageBuffer,+} from './log-record-avro'import type { CompiledMetricRule } from './metrics-rules/compile-metric-rules'import { MetricRulesCache } from './metrics-rules/metric-rules-cache'import { LogsMetricsEmitter } from './metrics-rules/metrics-emitter'@@ -309,6 +315,8 @@ export class LogsIngestionConsumer {private readonly transformationsKillswitch: booleanprivate readonly retentionEnabledTeamsRaw: stringprivate readonly retentionKillswitch: boolean+ private readonly patternMaskingEnabledTeamsRaw: string+ private readonly patternMaskingStage: PipelineStageprotected groupId: stringprotected topic: string@@ -358,6 +366,11 @@ export class LogsIngestionConsumer {this.transformationsKillswitch = mergedConfig.LOGS_TRANSFORMATIONS_KILLSWITCHthis.retentionEnabledTeamsRaw = mergedConfig.LOGS_RETENTION_ENABLED_TEAMSthis.retentionKillswitch = mergedConfig.LOGS_RETENTION_KILLSWITCH+ this.patternMaskingEnabledTeamsRaw = mergedConfig.LOGS_PATTERN_MASKING_ENABLED_TEAMS+ this.patternMaskingStage = makePatternMaskingStage(+ mergedConfig.LOGS_PATTERN_MASKING_MAX_INPUT_CHARS,+ mergedConfig.LOGS_PATTERN_MASKING_MAX_OUTPUT_CHARS+ )}private isSamplingEvalEnabledForTeam(teamId: number): boolean {@@ -388,6 +401,15 @@ export class LogsIngestionConsumer {return teamIdMatchesCsv(this.transformationsEnabledTeamsRaw, teamId)}+ /**+ * Logs only. `TracesIngestionConsumer` subclasses this one and reads the same config key, but a+ * trace record has no `body` field, so masking one measures nothing and would mix trace shapes+ * into the log-body split these metrics exist to produce.+ */+ private isPatternMaskingEnabledForTeam(teamId: number): boolean {+ return this.appSource === 'logs' && teamIdMatchesCsv(this.patternMaskingEnabledTeamsRaw, teamId)+ }+/*** Builds the hog log transformation hook for a message, or undefined when the team* is not gated in or has no enabled transformation_log functions (the existence@@ -476,6 +498,17 @@ export class LogsIngestionConsumer {stages.push(makeRetentionStage(retentionRuleSet, message.teamId, defaultRetentionDays))}+ // Runs last so it only sees survivors. Adding any stage forces the full decode and re-encode,+ // so a batch that would have passed through pays both, and one already decoded for a visitor+ // pays the encode. The counter prices each.+ if (this.isPatternMaskingEnabledForTeam(message.teamId)) {+ const modeWithoutMasking = bufferProcessingMode(logsSettings, stages.length, Boolean(onRecordsDecoded))+ if (modeWithoutMasking !== 'decode_and_reencode') {+ logsPatternForcedDecodeCounter.inc({ from: modeWithoutMasking })+ }+ stages.push(this.patternMaskingStage)+ }+trace.getActiveSpan()?.setAttributes({'logs.sampling.killswitch': this.samplingKillswitch,'logs.sampling.enabled_teams_configured': Boolean((this.samplingEnabledTeamsRaw || '').trim()),