: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): extract fields from a selected JSON attribute (#102938)
Jon McCallumb2770ef5de88
diff --git a/docs/published/docs/logs/logs-config.mdx b/docs/published/docs/logs/logs-config.mdxindex 751c1c339688..de9cadaf2d10 100644--- a/docs/published/docs/logs/logs-config.mdx+++ b/docs/published/docs/logs/logs-config.mdx@@ -66,7 +66,7 @@ Body enrichment has a 1 MiB byte budget for the body, severity text, and the keyFlattening visits at most 10,000 JSON nodes, allows a depth of 128, and budgets at most 1 MiB for generated paths and separately for retained serialized attributes. It retains at most 50 fields but continues the bounded traversal to preserve later collisions with those fields. If a size or traversal budget is exceeded, enrichment adds no fields and leaves the input record unchanged. Other configured ingestion stages still apply.-Operators can monitor `logs_ingestion_json_enrichment_skipped_total` with `reason` values `input_size`, `flatten_budget`, and `output_size`. These counts indicate skipped enrichment, not dropped logs.+Operators can monitor `logs_ingestion_json_enrichment_skipped_total` with `reason` values `input_size`, `flatten_budget`, and `output_size`. A `source` label separates `body` skips from `selected_attribute` skips. These counts cover enrichment skips, not dropped logs. Each source is checked independently, so a record can increment the counter more than once.## JSON attribute parsing configuration@@ -81,7 +81,22 @@ 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. No fields are extracted from the attribute yet.+### Extract fields from a JSON attribute++Extraction requires both a saved key and an operator rollout gate: `LOGS_JSON_ATTRIBUTE_EXTRACTION_ENABLED_TEAMS`. This new gate defaults to empty (disabled), accepts comma-separated project IDs or `*`, and runs only on logs, never traces. The existing probe allowlist does not enable extraction.++When enabled, PostHog parses the selected log attribute as a JSON object, including an object wrapped in a JSON string. Nested fields become dotted attributes prefixed with the selected key. For example, `payload` containing `{"user":{"id":"example-user"}}` adds `payload.user.id`.++- Sender-supplied attributes take precedence, followed by fields extracted from the selected attribute, then fields extracted from the JSON body.+- Nested arrays remain one JSON-string attribute at their object path. `payload` containing `{"flags":["alpha","beta"]}` adds `payload.flags`, not `payload.flags.0` or `payload.flags.1`. Array order and element types are preserved; this does not add native membership filtering.+- A top-level array, primitive, invalid JSON, or missing key adds no fields. String-wrapped top-level arrays also add no fields.+- Extraction does not remove or rewrite the source attribute. If PII scrubbing is enabled, it runs first and extraction uses the scrubbed source. Configured transformations and drop rules still run afterwards.++Each selected object contributes at most 50 fields; each nested array counts as one field. The depth, node, and byte budgets described above apply, including validation of the contents of retained arrays. Over-budget extraction adds no fields from that source. The combined record must remain within the shared 1 MiB content budget.++Extracted fields are available to log-based metrics and subsequent ingestion stages. To link logs to people or sessions, set **Link to person** or **Link to session** to the extracted path, such as `payload.personId` or `payload.sessionId`.++Enabling extraction moves otherwise-passthrough traffic to Avro decoding and re-encoding. Roll out to a small project allowlist and monitor ingestion lag, CPU, and enrichment skips. The `logs_ingestion_processing_duration_seconds` metric carries an `attribute_extraction_enabled` label, so you can separate this cost from body parsing and PII scrubbing. Clearing the new extraction allowlist disables extraction without disabling the probe.### Measure-only ingestion probediff --git a/nodejs/src/logs/config.ts b/nodejs/src/logs/config.tsindex 0a667c8c127f..ed4ad6382ba8 100644--- a/nodejs/src/logs/config.ts+++ b/nodejs/src/logs/config.ts@@ -68,6 +68,7 @@ export type LogsIngestionConsumerConfig = {/** Comma-separated team IDs, or `*` for all teams, or empty (default) to disable measure-only pattern masking. */LOGS_PATTERN_MASKING_ENABLED_TEAMS: stringLOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS: string+ LOGS_JSON_ATTRIBUTE_EXTRACTION_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@@ -122,6 +123,7 @@ export function getDefaultLogsIngestionConsumerConfig(): LogsIngestionConsumerCo// Off by default: enabling forces decode+re-encode for allowlisted teams.LOGS_PATTERN_MASKING_ENABLED_TEAMS: '',LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS: '',+ LOGS_JSON_ATTRIBUTE_EXTRACTION_ENABLED_TEAMS: '',LOGS_BILLING_PRORATE_ENABLED: false,LOGS_TRANSFORMATIONS_ENABLED_TEAMS: '',LOGS_TRANSFORMATIONS_KILLSWITCH: false,diff --git a/nodejs/src/logs/ingestion-otel-metrics.test.ts b/nodejs/src/logs/ingestion-otel-metrics.test.tsindex b24cc3867bc7..306a3ca222bf 100644--- a/nodejs/src/logs/ingestion-otel-metrics.test.ts+++ b/nodejs/src/logs/ingestion-otel-metrics.test.ts@@ -55,8 +55,8 @@ describe('ingestion-otel-metrics', () => {['recordJsonEnrichmentSkipped','logs_ingestion_json_enrichment_skipped_total',- () => recordJsonEnrichmentSkipped('output_size'),- { reason: 'output_size' },+ () => recordJsonEnrichmentSkipped('output_size', 'selected_attribute'),+ { reason: 'output_size', source: 'selected_attribute' },1,],[@@ -143,6 +143,7 @@ describe('ingestion-otel-metrics', () => {recordLogProcessingDuration(0.02, {json_parse_enabled: 'true',pii_scrub_enabled: 'false',+ attribute_extraction_enabled: 'false',compression_codec: 'snappy',}),],@@ -169,7 +170,12 @@ describe('ingestion-otel-metrics', () => {)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' }+ const attributes = {+ json_parse_enabled: 'true',+ pii_scrub_enabled: 'false',+ attribute_extraction_enabled: 'true',+ compression_codec: 'snappy',+ }recordLogProcessingDuration(0.02, attributes)await reader.forceFlush()diff --git a/nodejs/src/logs/ingestion-otel-metrics.ts b/nodejs/src/logs/ingestion-otel-metrics.tsindex c47d779b4879..0ba34752f381 100644--- a/nodejs/src/logs/ingestion-otel-metrics.ts+++ b/nodejs/src/logs/ingestion-otel-metrics.ts@@ -42,7 +42,7 @@ function getInstruments(): LogsIngestionInstruments {unit: 'By',}),jsonEnrichmentSkipped: createCounterWithExemplars(meter, 'logs_ingestion_json_enrichment_skipped_total', {- description: 'Log body JSON enrichment skipped because a size or traversal budget was exceeded',+ description: 'Log JSON enrichment skipped because a size or traversal budget was exceeded',}),recordsReceived: createCounterWithExemplars(meter, 'logs_ingestion_records_received_total', {description: 'Total log records received',@@ -89,8 +89,8 @@ export const recordLogsReceived = swallowing((bytes: number, records: number): vaddPositive(recordsReceived, records)})-export const recordJsonEnrichmentSkipped = swallowing((reason: string): void => {- getInstruments().jsonEnrichmentSkipped.add(1, { reason })+export const recordJsonEnrichmentSkipped = swallowing((reason: string, source: string): void => {+ getInstruments().jsonEnrichmentSkipped.add(1, { reason, source })})export const recordLogsAllowed = swallowing((bytes: number, records: number): void => {@@ -117,7 +117,12 @@ export const recordLogMessageDlq = swallowing((reason: string, teamId: string):export const recordLogProcessingDuration = swallowing((seconds: number,- attributes: { json_parse_enabled: string; pii_scrub_enabled: string; compression_codec: string }+ attributes: {+ json_parse_enabled: string+ pii_scrub_enabled: string+ attribute_extraction_enabled: string+ compression_codec: string+ }): void => {getInstruments().processingDuration.record(seconds, attributes)}diff --git a/nodejs/src/logs/log-record-avro.test.ts b/nodejs/src/logs/log-record-avro.test.tsindex c87bb63f177c..40f66b3d1dae 100644--- a/nodejs/src/logs/log-record-avro.test.ts+++ b/nodejs/src/logs/log-record-avro.test.ts@@ -9,9 +9,11 @@ import {bufferProcessingMode,decodeLogRecords,encodeLogRecords,+ enrichLogRecordFromJsonAttribute,enrichLogRecordWithJsonAttributes,extractJsonAttributesFromBody,flattenJson,+ logProcessingDurationHistogram,logsJsonAttributeSniffCounter,logsJsonEnrichmentSkippedCounter,processLogMessageBuffer,@@ -450,7 +452,7 @@ describe('log-record-avro', () => {expect(record).toEqual(original)expect(record.attributes).toBe(attributes)expect((await logsJsonEnrichmentSkippedCounter.get()).values).toEqual([- expect.objectContaining({ labels: { reason: 'output_size' }, value: 1 }),+ expect.objectContaining({ labels: { reason: 'output_size', source: 'body' }, value: 1 }),])} else {expect(record).toEqual({ ...original, attributes: { existing: 'true', a: '"é"' } })@@ -480,7 +482,7 @@ describe('log-record-avro', () => {expect(decoded).toEqual([{ ...record, bytes_uncompressed: null }])expect((await logsJsonEnrichmentSkippedCounter.get()).values).toEqual([- expect.objectContaining({ labels: { reason }, value: 1 }),+ expect.objectContaining({ labels: { reason, source: 'body' }, value: 1 }),])})@@ -597,6 +599,153 @@ describe('log-record-avro', () => {})})+ describe('selected JSON attribute extraction', () => {+ it.each([false, true])('extracts objects with string wrapping=%s and a literal dotted key', (wrapped) => {+ const json = JSON.stringify({ user: { id: 'synthetic-user' }, count: 3, enabled: true })+ const source = wrapped ? JSON.stringify(json) : json+ const record = createRecord({ attributes: { 'payload.json': source, 'payload.json.count': '9' } })++ enrichLogRecordFromJsonAttribute(record, 'payload.json')++ expect(record.attributes).toEqual({+ 'payload.json': source,+ 'payload.json.user.id': JSON.stringify('synthetic-user'),+ 'payload.json.count': '9',+ 'payload.json.enabled': 'true',+ })+ })++ it.each(+ [[], ['alpha', 'beta'], ['beta', 'alpha'], [{ id: 1 }], [null, 3, true, ['nested'], { id: 2 }]].map(+ (items) => [items]+ )+ )('retains nested array %j as a single JSON-string attribute', (items) => {+ const source = JSON.stringify({ values: items })+ const record = createRecord({ attributes: { payload: source } })++ enrichLogRecordFromJsonAttribute(record, 'payload')++ expect(record.attributes).toEqual({+ payload: source,+ 'payload.values': JSON.stringify(JSON.stringify(items)),+ })+ })++ it.each(['[]', '[1,2]', JSON.stringify('[1,2]'), 'null', 'true', '4', '"text"', '{broken', ''])(+ 'preserves non-object input %s without extracting fields',+ (source) => {+ const record = createRecord({ attributes: { payload: source } })+ const original = structuredClone(record)+ enrichLogRecordFromJsonAttribute(record, 'payload')+ expect(record).toEqual(original)+ }+ )++ it('counts each array as one retained field', () => {+ const source = JSON.stringify(+ Object.fromEntries(Array.from({ length: 60 }, (_, index) => [`key${index}`, []]))+ )+ const record = createRecord({ attributes: { payload: source } })+ enrichLogRecordFromJsonAttribute(record, 'payload')+ expect(Object.keys(record.attributes!)).toHaveLength(51)+ expect(record.attributes!['payload.key49']).toBe(JSON.stringify('[]'))+ expect(record.attributes!['payload.key50']).toBeUndefined()+ })++ it.each([+ ['input_size', JSON.stringify({ value: 'x'.repeat(MAX_LOG_RECORD_BYTES) })],+ ['output_size', JSON.stringify({ value: '😀'.repeat(150_000) })],+ ['flatten_budget', '{"child":'.repeat(130) + '1' + '}'.repeat(130)],+ ['flatten_budget', '{"values":' + '['.repeat(130) + '1' + ']'.repeat(130) + '}'],+ ['flatten_budget', JSON.stringify({ first: Array(6000).fill(0), second: Array(6000).fill(0) })],+ [+ 'flatten_budget',+ JSON.stringify(Object.fromEntries(Array.from({ length: 10_000 }, (_, index) => [index, 0]))),+ ],+ ])('skips %s atomically for oversized or complex input', async (reason, source) => {+ const record = createRecord({ attributes: { payload: source, original: 'true' } })+ const original = structuredClone(record)+ logsJsonEnrichmentSkippedCounter.reset()+ enrichLogRecordFromJsonAttribute(record, 'payload')+ expect(record).toEqual(original)+ expect((await logsJsonEnrichmentSkippedCounter.get()).values).toEqual([+ expect.objectContaining({ labels: { reason, source: 'selected_attribute' }, value: 1 }),+ ])+ })++ it('re-encodes attribute-only enrichment before decoded-record visitors', async () => {+ const record = createRecord({ attributes: { payload: JSON.stringify({ count: 7 }) } })+ const buffer = await encodeLogRecords(LOG_RECORD_SCHEMA, 'zstandard', [record])+ const visitor = jest.fn()+ logProcessingDurationHistogram.reset()+ const result = await processLogMessageBuffer(+ buffer,+ { json_parse_logs_attribute_key: 'payload' },+ { onRecordsDecoded: visitor }+ )+ const [, , records] = await decodeLogRecords(result.value!)+ expect(records[0].attributes).toEqual({ ...record.attributes, 'payload.count': '7' })+ expect(visitor.mock.calls[0][0][0].attributes).toEqual(records[0].attributes)+ expect(result.pii).toEqual({ piiReplacements: 0 })+ // Extraction-only traffic needs its own duration series. Without the label, its cost+ // merges into the bucket that body parsing, scrubbing and untransformed traffic share.+ expect((await logProcessingDurationHistogram.get()).values).toContainEqual(+ expect.objectContaining({+ metricName: 'logs_ingestion_processing_duration_seconds_count',+ labels: expect.objectContaining({+ json_parse_enabled: 'false',+ pii_scrub_enabled: 'false',+ attribute_extraction_enabled: 'true',+ }),+ value: 1,+ })+ )+ })++ it('gives sender attributes priority over selected JSON, then body JSON', async () => {+ const source = JSON.stringify({ sender: 'selected', selected: 'selected' })+ const record = createRecord({+ attributes: { payload: source, 'payload.sender': JSON.stringify('sender') },+ body: JSON.stringify({ payload: { sender: 'body', selected: 'body', body: 'body', items: [1] } }),+ })+ await transformDecodedLogRecordsInPlace([record], {+ json_parse_logs: true,+ json_parse_logs_attribute_key: 'payload',+ })+ expect(record.attributes).toEqual({+ payload: source,+ 'payload.sender': JSON.stringify('sender'),+ 'payload.selected': JSON.stringify('selected'),+ 'payload.body': JSON.stringify('body'),+ 'payload.items.0': '1',+ })+ })++ it('does not extract from a selected key introduced by body parsing', async () => {+ const record = createRecord({ attributes: null, body: JSON.stringify({ payload: '{"nested":true}' }) })+ await transformDecodedLogRecordsInPlace([record], {+ json_parse_logs: true,+ json_parse_logs_attribute_key: 'payload',+ })+ expect(record.attributes).toEqual({ payload: JSON.stringify('{"nested":true}') })+ })++ it('extracts from the scrubbed source rather than copying sensitive values', async () => {+ const record = createRecord({+ attributes: { payload: JSON.stringify({ authorization: 'Bearer synthetic_test_credential' }) },+ })+ const pii = await transformDecodedLogRecordsInPlace([record], {+ pii_scrub_logs: true,+ json_parse_logs_attribute_key: 'payload',+ })+ expect(pii.piiReplacements).toBeGreaterThan(0)+ expect(record.attributes).toEqual({+ payload: JSON.stringify({ authorization: `Bearer ${PII_REDACTED}` }),+ 'payload.authorization': JSON.stringify(`Bearer ${PII_REDACTED}`),+ })+ })+ })+describe('processLogMessageBuffer', () => {it('processes buffer with JSON parsing enabled', async () => {const records: LogRecord[] = [@@ -755,6 +904,8 @@ describe('log-record-avro', () => {['everything off', {}, 0, false, 'passthrough'],['json parse on', { json_parse_logs: true }, 0, false, 'decode_and_reencode'],['pii scrub on', { pii_scrub_logs: true }, 0, false, 'decode_and_reencode'],+ ['attribute extraction on', { json_parse_logs_attribute_key: 'payload' }, 0, false, 'decode_and_reencode'],+ ['empty attribute key', { json_parse_logs_attribute_key: '' }, 0, false, 'passthrough'],['a stage present', {}, 1, false, 'decode_and_reencode'],['a decoded-records visitor present', {}, 0, true, 'decode_only'],['a visitor and a stage', {}, 1, true, 'decode_and_reencode'],diff --git a/nodejs/src/logs/log-record-avro.ts b/nodejs/src/logs/log-record-avro.tsindex 50d6d782fcb3..1278153d5cdf 100644--- a/nodejs/src/logs/log-record-avro.ts+++ b/nodejs/src/logs/log-record-avro.ts@@ -4,6 +4,7 @@ import { Counter, Histogram } from 'prom-client'import { Readable } from 'stream'import { instrumented } from '~/common/tracing/tracing-utils'+import { parseJSON } from '~/common/utils/json-parse'import type { LogsSettings } from '~/types'import { recordJsonEnrichmentSkipped, recordLogProcessingDuration } from './ingestion-otel-metrics'@@ -30,10 +31,10 @@ const SPAN_LOGS_PROCESS_BUFFER = 'logsIngestionConsumer.handleEachBatch.processLconst logRecordProcessInstrumentOpts = { measureTime: false, sendException: false } as const-const logProcessingDurationHistogram = new Histogram({+export const logProcessingDurationHistogram = new Histogram({name: 'logs_ingestion_processing_duration_seconds',help: 'Time spent processing log messages (AVRO decode/encode cycle)',- labelNames: ['json_parse_enabled', 'pii_scrub_enabled', 'compression_codec'],+ labelNames: ['json_parse_enabled', 'pii_scrub_enabled', 'attribute_extraction_enabled', 'compression_codec'],buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1],})@@ -45,13 +46,19 @@ export const logsJsonAttributeSniffCounter = new Counter({export const logsJsonEnrichmentSkippedCounter = new Counter({name: 'logs_ingestion_json_enrichment_skipped_total',- help: 'Log body JSON enrichment skipped because a size or traversal budget was exceeded',- labelNames: ['reason'],+ help: 'Log JSON enrichment skipped because a size or traversal budget was exceeded',+ labelNames: ['reason', 'source'],})-function recordJsonEnrichmentSkip(reason: 'input_size' | 'flatten_budget' | 'output_size'): void {- logsJsonEnrichmentSkippedCounter.inc({ reason })- recordJsonEnrichmentSkipped(reason)+/** Which enrichment path hit the budget: the log body, or the configured JSON attribute. */+type JsonEnrichmentSource = 'body' | 'selected_attribute'++function recordJsonEnrichmentSkip(+ reason: 'input_size' | 'flatten_budget' | 'output_size',+ source: JsonEnrichmentSource+): void {+ logsJsonEnrichmentSkippedCounter.inc({ reason, source })+ recordJsonEnrichmentSkipped(reason, source)}export function sniffJsonLogAttributes(@@ -217,15 +224,39 @@ function isArrayIndex(key: string): boolean {return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === key}+function countJsonNodesWithinBudget(value: unknown, depth: number, budget: number): number | null {+ const stack = [{ value, depth }]+ let nodes = 1+ while (stack.length > 0) {+ const entry = stack.pop()!+ if (nodes > budget || entry.depth > MAX_JSON_DEPTH) {+ return null+ }+ if (entry.value !== null && typeof entry.value === 'object') {+ for (const key in entry.value) {+ if (!Object.hasOwn(entry.value, key)) {+ continue+ }+ if (++nodes > budget) {+ return null+ }+ stack.push({ value: (entry.value as Record<string, unknown>)[key], depth: entry.depth + 1 })+ }+ }+ }+ return nodes+}+/*** Flattens a JSON object into a flat key-value map with dot-notation keys.- * Arrays are indexed with numeric keys (e.g., "items.0.name").+ * Body arrays use indexed paths; selected-attribute arrays are stored as JSON strings.*/function flattenJsonWithBudget(obj: unknown,prefix = '',maxAttributes = MAX_JSON_ATTRIBUTES,- maxBytes = MAX_LOG_RECORD_BYTES+ maxBytes = MAX_LOG_RECORD_BYTES,+ arrayMode: 'indexed' | 'string' = 'indexed'): { values: Record<string, unknown>; attributes: Record<string, string> } | null {const result: Record<string, unknown> = {}const attributes: Record<string, string> = {}@@ -241,6 +272,14 @@ function flattenJsonWithBudget(if (entry.depth > MAX_JSON_DEPTH || pathBytes > maxBytes) {return null}+ if (arrayMode === 'string' && Array.isArray(entry.value)) {+ const arrayNodes = countJsonNodesWithinBudget(entry.value, entry.depth, MAX_JSON_NODES - nodes + 1)+ if (arrayNodes === null) {+ return null+ }+ nodes += arrayNodes - 1+ entry.value = JSON.stringify(entry.value)+ }if (entry.value !== null && typeof entry.value === 'object') {const value = entry.value as Record<string, unknown>if (Array.isArray(value) && value.length + nodes > MAX_JSON_NODES) {@@ -324,7 +363,7 @@ function jsonAttributesFromBodyParse(bodyParse: LogBodyParseResult): Record<striconst flattened = flattenJsonWithBudget(bodyParse.value)if (flattened === null) {- recordJsonEnrichmentSkip('flatten_budget')+ recordJsonEnrichmentSkip('flatten_budget', 'body')return {}}return flattened.attributes@@ -336,13 +375,18 @@ function jsonAttributesFromBodyParse(bodyParse: LogBodyParseResult): Record<stri*/export function extractJsonAttributesFromBody(body: string | null): Record<string, string> {if (body && Buffer.byteLength(body) > MAX_LOG_RECORD_BYTES) {- recordJsonEnrichmentSkip('input_size')+ recordJsonEnrichmentSkip('input_size', 'body')return {}}return jsonAttributesFromBodyParse(parseLogBodyForIngestion(body))}-function addJsonAttributes(record: LogRecord, jsonAttributes: Record<string, string>, recordBytes: number): void {+function addJsonAttributes(+ record: LogRecord,+ jsonAttributes: Record<string, string>,+ recordBytes: number,+ source: JsonEnrichmentSource+): void {if (Object.keys(jsonAttributes).length === 0) {return}@@ -350,7 +394,7 @@ function addJsonAttributes(record: LogRecord, jsonAttributes: Record<string, strif (!record.attributes || !Object.hasOwn(record.attributes, key)) {recordBytes += Buffer.byteLength(key) + Buffer.byteLength(value)if (recordBytes > MAX_LOG_RECORD_BYTES) {- recordJsonEnrichmentSkip('output_size')+ recordJsonEnrichmentSkip('output_size', source)return}}@@ -374,7 +418,7 @@ export function enrichLogRecordWithJsonAttributes(record: LogRecord, bodyParse?:}if (Buffer.byteLength(record.body) > MAX_LOG_RECORD_BYTES) {- recordJsonEnrichmentSkip('input_size')+ recordJsonEnrichmentSkip('input_size', 'body')return record}@@ -384,15 +428,44 @@ export function enrichLogRecordWithJsonAttributes(record: LogRecord, bodyParse?:}const recordBytes = logRecordSizeBytes(record)if (recordBytes > MAX_LOG_RECORD_BYTES) {- recordJsonEnrichmentSkip('input_size')+ recordJsonEnrichmentSkip('input_size', 'body')return record}const jsonAttributes = jsonAttributesFromBodyParse(parse)- addJsonAttributes(record, jsonAttributes, recordBytes)+ addJsonAttributes(record, jsonAttributes, recordBytes, 'body')return record}+export function enrichLogRecordFromJsonAttribute(record: LogRecord, key: string): void {+ if (!record.attributes || !Object.hasOwn(record.attributes, key)) {+ return+ }+ const recordBytes = logRecordSizeBytes(record)+ if (recordBytes > MAX_LOG_RECORD_BYTES) {+ recordJsonEnrichmentSkip('input_size', 'selected_attribute')+ return+ }+ let parsed: unknown+ try {+ parsed = parseJSON(record.attributes[key])+ if (typeof parsed === 'string') {+ parsed = parseJSON(parsed)+ }+ } catch {+ return+ }+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return+ }+ const flattened = flattenJsonWithBudget(parsed, key, MAX_JSON_ATTRIBUTES, MAX_LOG_RECORD_BYTES, 'string')+ if (flattened === null) {+ recordJsonEnrichmentSkip('flatten_budget', 'selected_attribute')+ return+ }+ addJsonAttributes(record, flattened.attributes, recordBytes, 'selected_attribute')+}+const enrichBatchJsonAttributes = instrumented({key: SPAN_LOGS_ENRICH_JSON,...logRecordProcessInstrumentOpts,@@ -415,9 +488,8 @@ const scrubBatch = instrumented({})/**- * Applies PII scrub and optional JSON parse + attribute enrichment to decoded records in place.- * Used by the main buffer processor and by the sampling path (which must decode even when- * json_parse / pii_scrub are off, then optionally runs this when either flag is on).+ * Scrub before extracting fields, then enrich from the selected attribute before the body so+ * sender attributes win over selected-attribute fields, which win over body-derived fields.*/export async function transformDecodedLogRecordsInPlace(records: LogRecord[],@@ -426,15 +498,17 @@ export async function transformDecodedLogRecordsInPlace(const jsonParse = settings.json_parse_logs ?? falseconst piiScrub = settings.pii_scrub_logs ?? falselet pii: PiiScrubStats = EMPTY_PII- if (jsonParse && piiScrub) {+ if (piiScrub) {pii = await scrubBatch(records)+ }+ if (settings.json_parse_logs_attribute_key) {+ for (const record of records) {+ enrichLogRecordFromJsonAttribute(record, settings.json_parse_logs_attribute_key)+ }+ }+ if (jsonParse) {const bodyParses = await parseLogBodiesForIngestion(records)await enrichBatchJsonAttributes(records, bodyParses)- } else if (jsonParse) {- const bodyParses = await parseLogBodiesForIngestion(records)- await enrichBatchJsonAttributes(records, bodyParses)- } else if (piiScrub) {- pii = await scrubBatch(records)}return pii}@@ -473,7 +547,10 @@ export function bufferProcessingMode(stageCount: number,hasVisitor: boolean): BufferProcessingMode {- const normalizeActive = (settings.json_parse_logs ?? false) || (settings.pii_scrub_logs ?? false)+ const normalizeActive =+ (settings.json_parse_logs ?? false) ||+ (settings.pii_scrub_logs ?? false) ||+ Boolean(settings.json_parse_logs_attribute_key)if (normalizeActive || stageCount > 0) {return 'decode_and_reencode'}@@ -482,9 +559,9 @@ export function bufferProcessingMode(/*** The single decode → transform → encode path for a log message buffer.- * Passthrough (no decode) when json_parse_logs and pii_scrub_logs are off, there are no `stages`, and- * no `onRecordsDecoded` visitor.- * Otherwise: decode → normalize (optional PII scrub on `body`, then optional JSON parse + enrich) →+ * Passthrough (no decode) when body parsing, attribute extraction and PII scrubbing are off,+ * there are no `stages`, and no `onRecordsDecoded` visitor.+ * Otherwise: decode → normalize (PII scrub, selected-attribute extraction, body enrichment) →* `onRecordsDecoded` visitor → run `stages` in order → encode.** When both `json_parse_logs` and `pii_scrub_logs` are on, scrub runs **before** parse/enrich so flattened JSON@@ -512,6 +589,7 @@ export const processLogMessageBuffer = instrumented({// Read only by the duration labels in the `finally`, which the passthrough return never reaches.const jsonParse = settings.json_parse_logs ?? falseconst piiScrub = settings.pii_scrub_logs ?? false+ const attributeExtraction = Boolean(settings.json_parse_logs_attribute_key)const startTime = Date.now()let codec = 'unknown'@@ -549,6 +627,7 @@ export const processLogMessageBuffer = instrumented({const durationLabels = {json_parse_enabled: String(jsonParse),pii_scrub_enabled: String(piiScrub),+ attribute_extraction_enabled: String(attributeExtraction),compression_codec: codec,}logProcessingDurationHistogram.observe(durationLabels, durationSeconds)diff --git a/nodejs/src/logs/logs-ingestion-consumer.test.ts b/nodejs/src/logs/logs-ingestion-consumer.test.tsindex e2e07f440c2e..8fb23df5619e 100644--- a/nodejs/src/logs/logs-ingestion-consumer.test.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.test.ts@@ -2071,6 +2071,51 @@ describe('LogsIngestionConsumer', () => {})})+ describe('JSON attribute extraction', () => {+ 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 only re-encodes eligible logs', async (_, allowlist, key, enabled) => {+ await consumer.stop()+ consumer = await createLogsIngestionConsumer(hub, {+ LOGS_JSON_ATTRIBUTE_EXTRACTION_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 },+ })+ const message = await createKafkaMessage(+ createLogMessage(),+ { token: team.api_token },+ { payload: JSON.stringify('{"count":7}') }+ )+ if (!enabled) {+ message.value = Buffer.from('disabled extraction must not decode')+ }+ await waitForBackgroundTasks(consumer.processKafkaBatch([message]))+ const output = getProducedKafkaMessages().filter((entry) => entry.topic === KAFKA_LOGS_CLICKHOUSE)+ expect(output).toHaveLength(1)+ if (enabled) {+ const [, , records] = await decodeLogRecords(output[0].value as Buffer)+ expect(records[0].attributes).toMatchObject({+ payload: JSON.stringify('{"count":7}'),+ 'payload.count': '7',+ })+ } else {+ expect(output[0].value).toEqual(message.value)+ }+ })+ })+describe('metric rules (generate metrics from logs)', () => {let mockEmitter: { emit: jest.Mock }let mockMetricRulesCache: Pick<MetricRulesCache, 'getCompiledRules'>@@ -2273,7 +2318,10 @@ describe('LogsIngestionConsumer', () => {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: '*' })+ consumer = createTracesIngestionConsumer({+ LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS: '*',+ LOGS_JSON_ATTRIBUTE_EXTRACTION_ENABLED_TEAMS: '*',+ })await consumer.start()jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({...team,diff --git a/nodejs/src/logs/logs-ingestion-consumer.ts b/nodejs/src/logs/logs-ingestion-consumer.tsindex a597bef4cecf..d43dee476b29 100644--- a/nodejs/src/logs/logs-ingestion-consumer.ts+++ b/nodejs/src/logs/logs-ingestion-consumer.ts@@ -369,6 +369,7 @@ export class LogsIngestionConsumer {private readonly retentionKillswitch: booleanprivate readonly patternMaskingEnabledTeamsRaw: stringprivate readonly jsonAttributeParsingEnabledTeamsRaw: string+ private readonly jsonAttributeExtractionEnabledTeamsRaw: stringprivate readonly patternMaskingStage: PipelineStageprotected groupId: string@@ -421,6 +422,7 @@ export class LogsIngestionConsumer {this.retentionKillswitch = mergedConfig.LOGS_RETENTION_KILLSWITCHthis.patternMaskingEnabledTeamsRaw = mergedConfig.LOGS_PATTERN_MASKING_ENABLED_TEAMSthis.jsonAttributeParsingEnabledTeamsRaw = mergedConfig.LOGS_JSON_ATTRIBUTE_PARSING_ENABLED_TEAMS+ this.jsonAttributeExtractionEnabledTeamsRaw = mergedConfig.LOGS_JSON_ATTRIBUTE_EXTRACTION_ENABLED_TEAMSthis.patternMaskingStage = makePatternMaskingStage()}@@ -958,7 +960,17 @@ export class LogsIngestionConsumer {async () =>this.resolveLogMessageBufferWithOptionalSampling(message,- logsSettings,+ {+ ...logsSettings,+ json_parse_logs_attribute_key:+ this.appSource === 'logs' &&+ teamIdMatchesCsv(+ this.jsonAttributeExtractionEnabledTeamsRaw,+ message.teamId+ )+ ? logsSettings.json_parse_logs_attribute_key+ : undefined,+ },onRecordsDecoded,transformationBatchBudget)