: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): dual-emit logs-ingestion usage metrics into the metrics product (#69560)
Daniel Viscab013bae407b4
diff --git a/nodejs/src/logs/ingestion-otel-metrics.test.ts b/nodejs/src/logs/ingestion-otel-metrics.test.tsnew file mode 100644index 000000000000..b58fe0056160--- /dev/null+++ b/nodejs/src/logs/ingestion-otel-metrics.test.ts@@ -0,0 +1,140 @@+import { metrics as metricsApi } from '@opentelemetry/api'+import {+ type DataPoint,+ type Histogram as HistogramDataPointValue,+ InMemoryMetricExporter,+ MeterProvider,+ PeriodicExportingMetricReader,+} from '@opentelemetry/sdk-metrics'++import {+ recordLogMessageDlq,+ recordLogMessageDropped,+ recordLogProcessingDuration,+ recordLogsAllowed,+ recordLogsDropped,+ recordLogsReceived,+ resetLogsIngestionInstrumentsForTests,+} from './ingestion-otel-metrics'++describe('ingestion-otel-metrics', () => {+ let exporter: InMemoryMetricExporter+ let provider: MeterProvider+ let reader: PeriodicExportingMetricReader++ beforeEach(() => {+ // Simulate the real startup-order hazard: a record call may run before a+ // provider exists (bound to the noop meter), with the provider registered+ // afterwards. Lazily acquired instruments must still deliver data recorded+ // after registration.+ resetLogsIngestionInstrumentsForTests()+ recordLogsReceived(1, 1)++ exporter = new InMemoryMetricExporter(0)+ reader = new PeriodicExportingMetricReader({ exporter, exportIntervalMillis: 60_000 })+ provider = new MeterProvider({ readers: [reader] })+ metricsApi.setGlobalMeterProvider(provider)+ resetLogsIngestionInstrumentsForTests()+ })++ afterEach(async () => {+ await provider.shutdown()+ metricsApi.disable()+ })++ const dataPointsFor = <T>(name: string): readonly DataPoint<T>[] =>+ exporter+ .getMetrics()+ .flatMap((rm) => rm.scopeMetrics)+ .flatMap((sm) => sm.metrics)+ .filter((m) => m.descriptor.name === name)+ .flatMap((m) => m.dataPoints as unknown as readonly DataPoint<T>[])++ it.each([+ [+ 'recordLogsReceived bytes',+ 'logs_ingestion_bytes_received_total',+ () => recordLogsReceived(3072, 15),+ {},+ 3072,+ ],+ [+ 'recordLogsReceived records',+ 'logs_ingestion_records_received_total',+ () => recordLogsReceived(3072, 15),+ {},+ 15,+ ],+ ['recordLogsAllowed bytes', 'logs_ingestion_bytes_allowed_total', () => recordLogsAllowed(1024, 5), {}, 1024],+ ['recordLogsAllowed records', 'logs_ingestion_records_allowed_total', () => recordLogsAllowed(1024, 5), {}, 5],+ [+ 'recordLogsDropped bytes',+ 'logs_ingestion_bytes_dropped_total',+ () => recordLogsDropped(42, 2048, 10),+ { team_id: '42' },+ 2048,+ ],+ [+ 'recordLogsDropped records',+ 'logs_ingestion_records_dropped_total',+ () => recordLogsDropped(42, 2048, 10),+ { team_id: '42' },+ 10,+ ],+ [+ 'recordLogMessageDropped',+ 'logs_ingestion_message_dropped_count',+ () => recordLogMessageDropped('rate_limited', '42', 3),+ { reason: 'rate_limited', team_id: '42' },+ 3,+ ],+ [+ 'recordLogMessageDlq',+ 'logs_ingestion_message_dlq_count',+ () => recordLogMessageDlq('KafkaError', '42'),+ { reason: 'KafkaError', team_id: '42' },+ 1,+ ],+ ] as const)('%s emits %s', async (_name, metricName, record, attributes, value) => {+ record()++ await reader.forceFlush()++ const points = dataPointsFor<number>(metricName)+ expect(points).toHaveLength(1)+ expect(points[0].attributes).toEqual(attributes)+ expect(points[0].value).toEqual(value)+ })++ it('skips zero and negative amounts so no empty per-team series are created', async () => {+ recordLogsDropped(42, 0, 0)+ recordLogsReceived(0, -1)+ recordLogMessageDropped('rate_limited', '42', 0)++ await reader.forceFlush()++ const names = [+ 'logs_ingestion_bytes_dropped_total',+ 'logs_ingestion_records_dropped_total',+ 'logs_ingestion_bytes_received_total',+ 'logs_ingestion_records_received_total',+ 'logs_ingestion_message_dropped_count',+ ]+ expect(names.map((name) => dataPointsFor(name).length)).toEqual([0, 0, 0, 0, 0])+ })++ it('records processing duration with the prom bucket ladder and pipeline attributes', async () => {+ const attributes = { json_parse_enabled: 'true', pii_scrub_enabled: 'false', compression_codec: 'snappy' }+ recordLogProcessingDuration(0.02, attributes)++ await reader.forceFlush()++ const points = dataPointsFor<HistogramDataPointValue>('logs_ingestion_processing_duration_seconds')+ expect(points).toHaveLength(1)+ expect(points[0].attributes).toEqual(attributes)+ expect(points[0].value.count).toEqual(1)+ expect(points[0].value.sum).toBeCloseTo(0.02)+ // Bucket parity with the prom histogram — dashboards translate 1:1 between the two sinks.+ expect(points[0].value.buckets.boundaries).toEqual([0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1])+ })+})diff --git a/nodejs/src/logs/ingestion-otel-metrics.ts b/nodejs/src/logs/ingestion-otel-metrics.tsnew file mode 100644index 000000000000..2b027de419de--- /dev/null+++ b/nodejs/src/logs/ingestion-otel-metrics.ts@@ -0,0 +1,117 @@+import { Attributes, Counter, Histogram, metrics as metricsApi } from '@opentelemetry/api'++/**+ * OTLP-pushed twins of the core logs-ingestion prom counters. The prom side keeps+ * feeding the scrape/VictoriaMetrics dashboards; these land in the PostHog metrics+ * product through the exporter installed by initMetrics (common/metrics/otel-metrics.ts),+ * with per-replica resource identity instead of the bridge's collapsed scrape identity.+ *+ * Names and label sets deliberately match the prom counters so dashboards translate 1:1.+ *+ * Instruments are acquired lazily on first record: the OTel metrics API has no proxy+ * provider, so instruments created at module load (before initMetrics runs) would be+ * bound to the noop meter forever.+ */++interface LogsIngestionInstruments {+ bytesReceived: Counter+ recordsReceived: Counter+ bytesAllowed: Counter+ recordsAllowed: Counter+ bytesDropped: Counter+ recordsDropped: Counter+ messagesDropped: Counter+ messagesDlq: Counter+ processingDuration: Histogram+}++/** Keep in lockstep with the logs_ingestion_processing_duration_seconds prom buckets. */+const PROCESSING_DURATION_BOUNDARIES = [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1]++let instruments: LogsIngestionInstruments | null = null++function getInstruments(): LogsIngestionInstruments {+ if (instruments === null) {+ const meter = metricsApi.getMeter('logs-ingestion')+ instruments = {+ bytesReceived: meter.createCounter('logs_ingestion_bytes_received_total', {+ description: 'Total uncompressed bytes received for logs ingestion',+ unit: 'By',+ }),+ recordsReceived: meter.createCounter('logs_ingestion_records_received_total', {+ description: 'Total log records received',+ }),+ bytesAllowed: meter.createCounter('logs_ingestion_bytes_allowed_total', {+ description: 'Total uncompressed bytes allowed through quota and rate limiting',+ unit: 'By',+ }),+ recordsAllowed: meter.createCounter('logs_ingestion_records_allowed_total', {+ description: 'Total log records allowed through quota and rate limiting',+ }),+ bytesDropped: meter.createCounter('logs_ingestion_bytes_dropped_total', {+ description: 'Total uncompressed bytes dropped due to quota or rate limiting',+ unit: 'By',+ }),+ recordsDropped: meter.createCounter('logs_ingestion_records_dropped_total', {+ description: 'Total log records dropped due to quota or rate limiting',+ }),+ messagesDropped: meter.createCounter('logs_ingestion_message_dropped_count', {+ description: 'The number of logs ingestion messages dropped',+ }),+ messagesDlq: meter.createCounter('logs_ingestion_message_dlq_count', {+ description: 'The number of logs ingestion messages sent to DLQ',+ }),+ processingDuration: meter.createHistogram('logs_ingestion_processing_duration_seconds', {+ description: 'Time spent processing log messages (AVRO decode/encode cycle)',+ unit: 's',+ advice: { explicitBucketBoundaries: PROCESSING_DURATION_BOUNDARIES },+ }),+ }+ }+ return instruments+}++function addPositive(counter: Counter, value: number, attributes?: Attributes): void {+ if (value > 0) {+ counter.add(value, attributes)+ }+}++export function recordLogsReceived(bytes: number, records: number): void {+ const { bytesReceived, recordsReceived } = getInstruments()+ addPositive(bytesReceived, bytes)+ addPositive(recordsReceived, records)+}++export function recordLogsAllowed(bytes: number, records: number): void {+ const { bytesAllowed, recordsAllowed } = getInstruments()+ addPositive(bytesAllowed, bytes)+ addPositive(recordsAllowed, records)+}++export function recordLogsDropped(teamId: number, bytes: number, records: number): void {+ const { bytesDropped, recordsDropped } = getInstruments()+ const attributes = { team_id: teamId.toString() }+ addPositive(bytesDropped, bytes, attributes)+ addPositive(recordsDropped, records, attributes)+}++export function recordLogMessageDropped(reason: string, teamId: string, count: number = 1): void {+ addPositive(getInstruments().messagesDropped, count, { reason, team_id: teamId })+}++export function recordLogMessageDlq(reason: string, teamId: string): void {+ getInstruments().messagesDlq.add(1, { reason, team_id: teamId })+}++export function recordLogProcessingDuration(+ seconds: number,+ attributes: { json_parse_enabled: string; pii_scrub_enabled: string; compression_codec: string }+): void {+ getInstruments().processingDuration.record(seconds, attributes)+}++/** Test seam: forget cached instruments so a test-installed provider is picked up. */+export function resetLogsIngestionInstrumentsForTests(): void {+ instruments = null+}diff --git a/nodejs/src/logs/log-record-avro.ts b/nodejs/src/logs/log-record-avro.tsindex dbea73f5531c..6f14a0b2f7dc 100644--- a/nodejs/src/logs/log-record-avro.ts+++ b/nodejs/src/logs/log-record-avro.ts@@ -6,6 +6,7 @@ import { Readable } from 'stream'import { instrumented } from '~/common/tracing/tracing-utils'import type { LogsSettings } from '~/types'+import { recordLogProcessingDuration } from './ingestion-otel-metrics'import { type LogBodyParseResult, parseLogBodyForIngestion } from './log-body-parse'import { EMPTY_PII, type PiiScrubStats, scrubLogRecord } from './log-pii-scrub'@@ -328,13 +329,12 @@ export const processLogMessageBuffer = instrumented({return { value, pii }} finally {const durationSeconds = (Date.now() - startTime) / 1000- logProcessingDurationHistogram.observe(- {- json_parse_enabled: String(jsonParse),- pii_scrub_enabled: String(piiScrub),- compression_codec: codec,- },- durationSeconds- )+ const durationLabels = {+ json_parse_enabled: String(jsonParse),+ pii_scrub_enabled: String(piiScrub),+ compression_codec: codec,+ }+ logProcessingDurationHistogram.observe(durationLabels, durationSeconds)+ recordLogProcessingDuration(durationSeconds, durationLabels)}}) as (buffer: Buffer, settings: LogsSettings) => Promise<{ value: Buffer; pii: PiiScrubStats }>diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.tsindex 818fe4c6e869..83d414a901b9 100644--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts@@ -1,5 +1,12 @@import { mockProducer, mockProducerObserver } from '~/tests/helpers/mocks/producer.mock'+import { metrics as metricsApi } from '@opentelemetry/api'+import {+ type DataPoint,+ InMemoryMetricExporter,+ MeterProvider,+ PeriodicExportingMetricReader,+} from '@opentelemetry/sdk-metrics'import { DateTime } from 'luxon'import { Message } from 'node-rdkafka'@@ -16,6 +23,7 @@ import { createTeam, getFirstTeam, getTeam, resetTestDatabase } from '~/tests/heimport { Hub, Team } from '~/types'import { getDefaultTracesIngestionConsumerConfig } from './config'+import { resetLogsIngestionInstrumentsForTests } from './ingestion-otel-metrics'import { LogRecord, encodeLogRecords } from './log-record-avro'import {DEFAULT_LOGS_RETENTION_DAYS,@@ -743,6 +751,68 @@ describe('LogsIngestionConsumer', () => {)})+ it('dual-emits usage counters into the OTel metrics push', async () => {+ // Wiring guard: the unit tests on ingestion-otel-metrics prove the record+ // functions work; this proves the consumer actually calls them.+ const otelExporter = new InMemoryMetricExporter(0)+ const otelReader = new PeriodicExportingMetricReader({+ exporter: otelExporter,+ exportIntervalMillis: 60_000,+ })+ const otelProvider = new MeterProvider({ readers: [otelReader] })+ metricsApi.setGlobalMeterProvider(otelProvider)+ resetLogsIngestionInstrumentsForTests()++ try {+ hub.LOGS_LIMITER_BUCKET_SIZE_KB = 2+ hub.LOGS_LIMITER_REFILL_RATE_KB_PER_SECOND = 1+ hub.LOGS_LIMITER_TTL_SECONDS = 3600++ await consumer.stop()+ consumer = await createLogsIngestionConsumer(hub)++ const messages = [+ ...(await createKafkaMessages([createLogMessage({ message: 'First' })], {+ token: team.api_token,+ bytes_uncompressed: '1024',+ bytes_compressed: '512',+ record_count: '5',+ })),+ ...(await createKafkaMessages([createLogMessage({ message: 'Second' })], {+ token: team.api_token,+ bytes_uncompressed: '2048',+ bytes_compressed: '1024',+ record_count: '10',+ })),+ ]++ await waitForBackgroundTasks(consumer.processKafkaBatch(messages))+ await otelReader.forceFlush()++ const pointsByMetric = new Map(+ otelExporter+ .getMetrics()+ .flatMap((rm) => rm.scopeMetrics)+ .flatMap((sm) => sm.metrics)+ .map((m) => [m.descriptor.name, m.dataPoints as readonly DataPoint<number>[]])+ )+ expect(pointsByMetric.get('logs_ingestion_bytes_received_total')?.[0]?.value).toEqual(3072)+ expect(pointsByMetric.get('logs_ingestion_bytes_allowed_total')?.[0]?.value).toEqual(1024)+ expect(pointsByMetric.get('logs_ingestion_bytes_dropped_total')?.[0]).toMatchObject({+ attributes: { team_id: team.id.toString() },+ value: 2048,+ })+ expect(pointsByMetric.get('logs_ingestion_message_dropped_count')?.[0]).toMatchObject({+ attributes: { reason: 'rate_limited', team_id: team.id.toString() },+ value: 1,+ })+ } finally {+ await otelProvider.shutdown()+ metricsApi.disable()+ resetLogsIngestionInstrumentsForTests()+ }+ })+it('should handle missing header values with defaults', async () => {const logData = createLogMessage()const messages = await createKafkaMessages([logData], {diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.tsindex e95629c45706..ec182248e31c 100644--- a/nodejs/src/logs/logs-ingestion-consumer.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.ts@@ -18,6 +18,13 @@ import type { LogsSettings } from '~/types'import { HealthCheckResult, PluginServerService } from '~/types'import { LogsIngestionConsumerConfig } from './config'+import {+ recordLogMessageDlq,+ recordLogMessageDropped,+ recordLogsAllowed,+ recordLogsDropped,+ recordLogsReceived,+} from './ingestion-otel-metrics'import { type PiiScrubStats } from './log-pii-scrub'import { processLogMessageBuffer } from './log-record-avro'import { LOGS_DLQ_OUTPUT, LOGS_OUTPUT, LogsDlqOutput, LogsOutput } from './outputs/outputs'@@ -422,6 +429,7 @@ export class LogsIngestionConsumer {}logsBytesReceivedCounter.inc(totalBytesReceived)logsRecordsReceivedCounter.inc(totalRecordsReceived)+ recordLogsReceived(totalBytesReceived, totalRecordsReceived)}private trackOutgoingTrafficAndBuildUsageStats(@@ -451,6 +459,7 @@ export class LogsIngestionConsumer {// Gross, before the drop-rule billing credit applied in processAndProduceLogMessages (see counter help).logsBytesAllowedCounter.inc(totalBytesAllowed)logsRecordsAllowedCounter.inc(totalRecordsAllowed)+ recordLogsAllowed(totalBytesAllowed, totalRecordsAllowed)for (const message of droppedMessages) {const stats = usageStats.get(message.teamId) || { ...DEFAULT_USAGE_STATS }@@ -469,6 +478,7 @@ export class LogsIngestionConsumer {if (stats.recordsDropped > 0) {logsRecordsDroppedCounter.inc({ team_id: teamIdLabel }, stats.recordsDropped)}+ recordLogsDropped(teamId, stats.bytesDropped, stats.recordsDropped)}return usageStats@@ -516,6 +526,7 @@ export class LogsIngestionConsumer {for (const [teamId, count] of droppedCountByTeam) {logMessageDroppedCounter.inc({ reason: 'quota_limited', team_id: teamId.toString() }, count)+ recordLogMessageDropped('quota_limited', teamId.toString(), count)}return { quotaAllowedMessages, quotaDroppedMessages }@@ -533,6 +544,7 @@ export class LogsIngestionConsumer {}for (const [teamId, count] of droppedCountByTeam) {logMessageDroppedCounter.inc({ reason: 'rate_limited', team_id: teamId.toString() }, count)+ recordLogMessageDropped('rate_limited', teamId.toString(), count)}return { rateLimiterAllowedMessages: allowed, rateLimiterDroppedMessages: dropped }@@ -651,6 +663,7 @@ export class LogsIngestionConsumer {{ reason: 'sampling_all_dropped', team_id: message.teamId.toString() },1)+ recordLogMessageDropped('sampling_all_dropped', message.teamId.toString())this.addPiiStatsIntoUsage(usageStats, message.teamId, resolved.pii)this.queueSamplingRecordsDroppedByRule(message.teamId, resolved.recordsDroppedByRuleId)this.queueBytesDroppedByRule(message.teamId, resolved.bytesDroppedByRuleId)@@ -706,6 +719,7 @@ export class LogsIngestionConsumer {const errorName = error instanceof Error ? error.name : 'UnknownError'logMessageDlqCounter.inc({ reason: errorName, team_id: message.teamId.toString() })+ recordLogMessageDlq(errorName, message.teamId.toString())try {await this.deps.outputs.queueMessages(LOGS_DLQ_OUTPUT, [@@ -828,6 +842,7 @@ export class LogsIngestionConsumer {if (!token) {logger.error('missing_token')logMessageDroppedCounter.inc({ reason: 'missing_token', team_id: 'unknown' })+ recordLogMessageDropped('missing_token', 'unknown')return}@@ -842,12 +857,14 @@ export class LogsIngestionConsumer {} catch (e) {logger.error('team_lookup_error', { error: e })logMessageDroppedCounter.inc({ reason: 'team_lookup_error', team_id: 'unknown' })+ recordLogMessageDropped('team_lookup_error', 'unknown')return}if (!team) {logger.error('team_not_found', { token_with_no_team: token })logMessageDroppedCounter.inc({ reason: 'team_not_found', team_id: 'unknown' })+ recordLogMessageDropped('team_not_found', 'unknown')return}@@ -874,6 +891,7 @@ export class LogsIngestionConsumer {} catch (e) {logger.error('Error parsing message', e)logMessageDroppedCounter.inc({ reason: 'parse_error', team_id: 'unknown' })+ recordLogMessageDropped('parse_error', 'unknown')return}})