Skip to content

: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.

feat(logs): add per-team json attribute sniff metrics (#101599)

Jon McCallum6dff0872e038
diff --git a/docs/published/docs/logs/logs-config.mdx b/docs/published/docs/logs/logs-config.mdx
index 227c931032af..13228cf15db9 100644
--- a/docs/published/docs/logs/logs-config.mdx
+++ b/docs/published/docs/logs/logs-config.mdx
@@ -71,4 +71,24 @@ The project API stores the key in `logs_settings.json_parse_logs_attribute_key`,
- The default is off. An empty string disables parsing.
- The API replaces the entire `logs_settings` object. Include the other current settings when updating it, as the UI does. Sending `logs_settings: null` clears all Logs settings.
-Saving a key records your choice. Ingestion does not read it yet, so no fields are extracted from the attribute.
+Saving a key records your choice. No fields are extracted from the attribute yet.
+
+### Measure-only ingestion probe
+
+Operators can set `LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS` to a comma-separated list of project IDs to enable a JSON-prefix probe. The default is empty (disabled); `*` enables all projects with a nonempty `json_parse_logs_attribute_key`. This probe runs only on logs, never traces.
+
+The Prometheus counter `logs_ingestion_json_attribute_sniff_total` has `team_id` and `outcome` labels. Each inspected record increments one outcome:
+
+- `missing_key`: the configured key is absent from the log attributes.
+- `looks_like_json`: the first 64 characters start with `{` or `[`, allowing leading whitespace and a JSON string's opening quote and escaped whitespace.
+- `other`: the key exists but does not match that prefix.
+
+This is a heuristic, not JSON validation. The probe does not parse JSON, flatten values, extract fields, or change records. Attribute names and values are not included in the metric. Records are inspected after existing PII scrubbing and body enrichment, before drop rules.
+
+Enabling the probe can add Avro decoding for traffic that would otherwise pass through untouched. Probe-only batches retain their original bytes without re-encoding. Use a small project allowlist to limit that cost and metric cardinality.
+
+To break down the observed record rate by project and outcome in Grafana:
+
+```promql
+sum by (team_id, outcome) (rate(logs_ingestion_json_attribute_sniff_total[5m]))
+```
diff --git a/nodejs/src/logs/config.ts b/nodejs/src/logs/config.ts
index a5c779477af0..0a667c8c127f 100644
--- a/nodejs/src/logs/config.ts
+++ b/nodejs/src/logs/config.ts
@@ -67,6 +67,7 @@ export type LogsIngestionConsumerConfig = {
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
+ LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS: string
/**
* 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
@@ -120,6 +121,7 @@ export function getDefaultLogsIngestionConsumerConfig(): LogsIngestionConsumerCo
LOGS_RETENTION_KILLSWITCH: false,
// Off by default: enabling forces decode+re-encode for allowlisted teams.
LOGS_PATTERN_MASKING_ENABLED_TEAMS: '',
+ LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS: '',
LOGS_BILLING_PRORATE_ENABLED: false,
LOGS_TRANSFORMATIONS_ENABLED_TEAMS: '',
LOGS_TRANSFORMATIONS_KILLSWITCH: false,
diff --git a/nodejs/src/logs/log-record-avro.test.ts b/nodejs/src/logs/log-record-avro.test.ts
index 913de50db75b..c3b27f9dc799 100644
--- a/nodejs/src/logs/log-record-avro.test.ts
+++ b/nodejs/src/logs/log-record-avro.test.ts
@@ -12,7 +12,9 @@ import {
enrichLogRecordWithJsonAttributes,
extractJsonAttributesFromBody,
flattenJson,
+ logsJsonAttributeSniffCounter,
processLogMessageBuffer,
+ sniffJsonLogAttributes,
} from './log-record-avro'
const LOG_RECORD_SCHEMA = avro.parse(`{
@@ -111,6 +113,34 @@ const LOG_RECORD_SCHEMA = avro.parse(`{
}`)
describe('log-record-avro', () => {
+ describe('sniffJsonLogAttributes', () => {
+ it.each([
+ [null, 'missing_key'],
+ [{}, 'missing_key'],
+ [{ payload: '{}' }, 'missing_key'],
+ [{ 'payload.json': '{}' }, 'looks_like_json'],
+ [{ 'payload.json': ' \n\t[1]' }, 'looks_like_json'],
+ [{ 'payload.json': JSON.stringify('{"nested":true}') }, 'looks_like_json'],
+ [{ 'payload.json': JSON.stringify('\n\t [1]') }, 'looks_like_json'],
+ [{ 'payload.json': '{not valid JSON' }, 'looks_like_json'],
+ [{ 'payload.json': '"ordinary text"' }, 'other'],
+ [{ 'payload.json': 'null' }, 'other'],
+ [{ 'payload.json': '' }, 'other'],
+ [{ 'payload.json': ' '.repeat(64) + '{}' }, 'other'],
+ ] as const)('classifies %j as %s without mutating the record', async (attributes, outcome) => {
+ logsJsonAttributeSniffCounter.reset()
+ const record = Object.freeze({ attributes: attributes && Object.freeze(attributes) })
+
+ sniffJsonLogAttributes([record], 'payload.json', 123)
+ sniffJsonLogAttributes([record, record], 'payload.json', 456)
+
+ expect((await logsJsonAttributeSniffCounter.get()).values).toEqual([
+ expect.objectContaining({ labels: { team_id: '123', outcome }, value: 1 }),
+ expect.objectContaining({ labels: { team_id: '456', outcome }, value: 2 }),
+ ])
+ })
+ })
+
describe('flattenJson', () => {
it.each([
['flattens simple object', { a: 'b', c: 'd' }, { a: 'b', c: 'd' }],
diff --git a/nodejs/src/logs/log-record-avro.ts b/nodejs/src/logs/log-record-avro.ts
index e41fabd8e121..d10f4dfd9e52 100644
--- a/nodejs/src/logs/log-record-avro.ts
+++ b/nodejs/src/logs/log-record-avro.ts
@@ -1,6 +1,6 @@
import { compress, decompress } from '@mongodb-js/zstd'
import avro from 'avsc'
-import { Histogram } from 'prom-client'
+import { Counter, Histogram } from 'prom-client'
import { Readable } from 'stream'
import { instrumented } from '~/common/tracing/tracing-utils'
@@ -34,6 +34,27 @@ const logProcessingDurationHistogram = new Histogram({
buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1],
})
+export const logsJsonAttributeSniffCounter = new Counter({
+ name: 'logs_ingestion_json_attribute_sniff_total',
+ help: 'Log records inspected for a configured JSON attribute prefix, without parsing or extracting fields',
+ labelNames: ['team_id', 'outcome'],
+})
+
+export function sniffJsonLogAttributes(
+ records: readonly Pick<LogRecord, 'attributes'>[],
+ attributeKey: string,
+ teamId: number
+): void {
+ for (const record of records) {
+ let outcome: 'missing_key' | 'looks_like_json' | 'other' = 'missing_key'
+ if (record.attributes && Object.hasOwn(record.attributes, attributeKey)) {
+ const value = record.attributes[attributeKey]
+ outcome = /^[ \t\r\n]*"?(?:[ \t\r\n]|\\[nrt])*[{\[]/.test(value.slice(0, 64)) ? 'looks_like_json' : 'other'
+ }
+ logsJsonAttributeSniffCounter.inc({ team_id: String(teamId), outcome })
+ }
+}
+
export interface LogRecord {
uuid: string | null
trace_id: Buffer | null
diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.ts
index 48b92a915324..e2e07f440c2e 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts
@@ -29,7 +29,7 @@ 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 { LogRecord, decodeLogRecords, encodeLogRecords, logsJsonAttributeSniffCounter } from './log-record-avro'
import {
DEFAULT_LOGS_RETENTION_DAYS,
LogsIngestionConsumer,
@@ -71,7 +71,11 @@ jest.mock('~/common/utils/posthog', () => {
let offsetIncrementer = 0
-const createKafkaMessage = async (logData: any, headers: Record<string, string> = {}): Promise<Message> => {
+const createKafkaMessage = async (
+ logData: any,
+ headers: Record<string, string> = {},
+ attributes: Record<string, string> | null = null
+): Promise<Message> => {
// Create a LogRecord from the log data
const record: LogRecord = {
uuid: `test-uuid-${offsetIncrementer}`,
@@ -87,7 +91,7 @@ const createKafkaMessage = async (logData: any, headers: Record<string, string>
resource_attributes: null,
instrumentation_scope: null,
event_name: null,
- attributes: null,
+ attributes,
}
// Encode as AVRO
@@ -2017,6 +2021,56 @@ describe('LogsIngestionConsumer', () => {
})
})
+ describe('JSON attribute sniffing', () => {
+ it.each([
+ ['disabled', '', 'payload', false],
+ ['different team', 'other_team', 'payload', false],
+ ['allowlisted team', 'this_team', 'payload', true],
+ ['wildcard', '*', 'payload', true],
+ ['missing setting', '*', undefined, false],
+ ['empty setting', '*', '', false],
+ ] as const)('%s preserves output and only counts eligible teams', async (_, allowlist, key, enabled) => {
+ await consumer.stop()
+ consumer = await createLogsIngestionConsumer(hub, {
+ LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS:
+ allowlist === 'this_team'
+ ? ` ${team.id}, ${team2.id} `
+ : allowlist === 'other_team'
+ ? String(team2.id)
+ : allowlist,
+ })
+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({
+ ...team,
+ logs_settings: { json_parse_logs_attribute_key: key },
+ })
+ logsJsonAttributeSniffCounter.reset()
+ const message = await createKafkaMessage(
+ createLogMessage(),
+ { token: team.api_token },
+ { payload: JSON.stringify('{"nested":true}') }
+ )
+ if (!enabled) {
+ message.value = Buffer.from('passthrough does not require Avro decoding')
+ }
+
+ await waitForBackgroundTasks(consumer.processKafkaBatch([message]))
+
+ const logsOutput = getProducedKafkaMessages().filter((output) => output.topic === KAFKA_LOGS_CLICKHOUSE)
+ expect(logsOutput).toHaveLength(1)
+ expect(logsOutput[0].value).toEqual(message.value)
+ expect((await logsJsonAttributeSniffCounter.get()).values).toEqual(
+ enabled
+ ? [
+ expect.objectContaining({
+ labels: { team_id: String(team.id), outcome: 'looks_like_json' },
+ value: 1,
+ }),
+ ]
+ : []
+ )
+ })
+ })
+
describe('metric rules (generate metrics from logs)', () => {
let mockEmitter: { emit: jest.Mock }
let mockMetricRulesCache: Pick<MetricRulesCache, 'getCompiledRules'>
@@ -2054,6 +2108,12 @@ describe('LogsIngestionConsumer', () => {
}
it('emits one OTLP payload per team with counts grouped by the rule dimensions', async () => {
+ await createConsumerWithMetricRules({ LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS: '*' })
+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({
+ ...team,
+ logs_settings: { json_parse_logs_attribute_key: 'payload' },
+ })
+ logsJsonAttributeSniffCounter.reset()
const messages = await createKafkaMessages(
[
createLogMessage({ level: 'info' }),
@@ -2073,6 +2133,12 @@ describe('LogsIngestionConsumer', () => {
emittedDataPoints().map((dp: any) => [dp.attributes[0].value.stringValue, dp.asDouble])
)
expect(bySeverity).toEqual({ info: 2, error: 1 })
+ expect((await logsJsonAttributeSniffCounter.get()).values).toEqual([
+ expect.objectContaining({
+ labels: { team_id: String(team.id), outcome: 'missing_key' },
+ value: 3,
+ }),
+ ])
})
it('produces logs normally when the rules cache fetch throws (fail-open)', async () => {
@@ -2205,6 +2271,26 @@ describe('LogsIngestionConsumer', () => {
expect(tracesConsumer['isPatternMaskingEnabledForTeam'](team.id)).toEqual(false)
})
+ it('never sniffs or decodes traces for a configured JSON attribute on a wildcard allowlist', async () => {
+ await consumer.stop()
+ consumer = createTracesIngestionConsumer({ LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS: '*' })
+ await consumer.start()
+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({
+ ...team,
+ logs_settings: { json_parse_logs_attribute_key: 'payload' },
+ })
+ logsJsonAttributeSniffCounter.reset()
+ const message = await createKafkaMessage(createLogMessage(), { token: team.api_token })
+ message.value = Buffer.from('trace payload must not be decoded as logs')
+
+ await waitForBackgroundTasks(consumer.processKafkaBatch([message]))
+
+ const tracesOutput = getProducedKafkaMessages().filter((output) => output.topic === KAFKA_LOGS_CLICKHOUSE)
+ expect(tracesOutput).toHaveLength(1)
+ expect(tracesOutput[0].value).toEqual(message.value)
+ expect((await logsJsonAttributeSniffCounter.get()).values).toEqual([])
+ })
+
it('meters usage as traces, not logs', async () => {
const tracesConsumer = createTracesIngestionConsumer()
tracesConsumer['queueUsageMetric'](team.id, 'bytes_ingested', 500)
diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.ts
index 1f82226bf47c..b2bc65a4966c 100644
--- a/nodejs/src/logs/logs-ingestion-consumer.ts
+++ b/nodejs/src/logs/logs-ingestion-consumer.ts
@@ -36,6 +36,7 @@ import {
type LogRecordsTransform,
bufferProcessingMode,
processLogMessageBuffer,
+ sniffJsonLogAttributes,
} from './log-record-avro'
import type { CompiledMetricRule, MetricRuleSource } from './metrics-rules/compile-metric-rules'
import { MetricRulesCache } from './metrics-rules/metric-rules-cache'
@@ -367,6 +368,7 @@ export class LogsIngestionConsumer {
private readonly retentionEnabledTeamsRaw: string
private readonly retentionKillswitch: boolean
private readonly patternMaskingEnabledTeamsRaw: string
+ private readonly jsonAttributeParsingEnabledTeamsRaw: string
private readonly patternMaskingStage: PipelineStage
protected groupId: string
@@ -418,6 +420,7 @@ export class LogsIngestionConsumer {
this.retentionEnabledTeamsRaw = mergedConfig.LOGS_RETENTION_ENABLED_TEAMS
this.retentionKillswitch = mergedConfig.LOGS_RETENTION_KILLSWITCH
this.patternMaskingEnabledTeamsRaw = mergedConfig.LOGS_PATTERN_MASKING_ENABLED_TEAMS
+ this.jsonAttributeParsingEnabledTeamsRaw = mergedConfig.LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS
this.patternMaskingStage = makePatternMaskingStage()
}
@@ -920,10 +923,27 @@ export class LogsIngestionConsumer {
}
const metricRuleState = await this.getMetricRuleBatchState(metricTalliesByTeam, message)
- const onRecordsDecoded = metricRuleState
- ? (records: LogRecord[]) =>
- tallyRecords(metricRuleState.rules, records, metricRuleState.tallies, Date.now())
- : undefined
+ const jsonAttributeKey =
+ this.appSource === 'logs' &&
+ teamIdMatchesCsv(this.jsonAttributeParsingEnabledTeamsRaw, message.teamId)
+ ? logsSettings.json_parse_logs_attribute_key
+ : undefined
+ const onRecordsDecoded =
+ metricRuleState || jsonAttributeKey
+ ? (records: LogRecord[]) => {
+ if (metricRuleState) {
+ tallyRecords(
+ metricRuleState.rules,
+ records,
+ metricRuleState.tallies,
+ Date.now()
+ )
+ }
+ if (jsonAttributeKey) {
+ sniffJsonLogAttributes(records, jsonAttributeKey, message.teamId)
+ }
+ }
+ : undefined
const resolved = await instrumentFn(
{
diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts
index bdd7dc4a1062..db8d5e5c9755 100644
--- a/nodejs/src/types.ts
+++ b/nodejs/src/types.ts
@@ -256,6 +256,7 @@ export interface EventSchemaEnforcement {
export interface LogsSettings {
capture_console_logs?: boolean
json_parse_logs?: boolean
+ json_parse_logs_attribute_key?: string
pii_scrub_logs?: boolean
retention_days?: number
retention_last_updated?: string