From ee45321e0840b4d9389206c59f9eba477b93561a Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 2 Dec 2026 22:45:12 +0800 Subject: [PATCH 1/2] fix(append-opentelemetry): emit unique log attribute keys by default The Rust SDK appends log attributes as supplied, so a diagnostic and an event field with the same key can both reach an OTLP receiver. Apply source location, diagnostics, and explicit record fields in increasing precedence. Keep the last occurrence of each key in source order. Add allow_duplicate_keys() for callers that manage key uniqueness themselves. Signed-off-by: tison --- CHANGELOG.md | 1 + DESIGN.md | 2 +- appenders/opentelemetry/README.md | 5 +- appenders/opentelemetry/src/lib.rs | 74 ++++++++++++++----- .../tests/append_test/opentelemetry.rs | 55 +++++++++++++- 5 files changed, 111 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65b43e90..042cb3f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -112,6 +112,7 @@ All significant changes to this project will be documented in this file. * `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging` now gives explicit `Record` key-values precedence over colliding `Diagnostic` entries. * `Async` in `logforth-append-async` now flushes inner appenders on `Drop` after draining queued records, isolates panics in inner appenders and `ErrorSink` during `append`, `flush`, and shutdown instead of terminating the worker thread or panicking in `Drop`, and waits for full bounded queues to drain during `flush` under `overflow_drop_incoming`. * `File` in `logforth-append-file` now opens segment files in append mode so external truncation does not leave NUL holes, and no longer panics or truncates timestamps and file sizes on matching prefix/suffix edge cases, out-of-range timestamps, or 32-bit targets. +* `OpentelemetryLog` in `logforth-append-opentelemetry` now emits unique log attribute keys by default, with explicit record fields overriding diagnostics and diagnostics overriding source location. Use `allow_duplicate_keys()` to pass repeated attributes to the SDK. * `OpentelemetryLog` in `logforth-append-opentelemetry` now sets `LogRecord::set_timestamp` from `Record::time()` instead of overwriting the event timestamp with `SystemTime::now()`. * `SocketSyslog` in `logforth-append-syslog` now formats syslog header timestamps from `Record::time()` instead of overwriting them with `SystemTime::now()`, and omits the RFC 3164 `HOSTNAME` token on local Unix socket builders (`SocketSyslogBuilder::{unix, unix_datagram, unix_stream}`) so `systemd-journald` and `rsyslog` parse `TAG[PID]` accurately. * `ThreadLocalDiagnostic` and `TaskLocalDiagnostic` no longer panic when logging during thread-local teardown, degrading to an empty context instead. diff --git a/DESIGN.md b/DESIGN.md index f533d1b4..e8057822 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -71,5 +71,5 @@ Logforth separates three concerns into distinct primitives: ### Precedence and Reserved Top-Level Fields -- Structured key-values and diagnostic entries are visited and emitted in order without cross-source deduplication unless a target format merges both into a single map (such as `GoogleCloudLoggingLayout`, where explicit `Record::key_values()` override colliding `Diagnostic` entries). +- Structured key-values and diagnostic entries are visited in order. Outputs that require unique keys, including `GoogleCloudLoggingLayout` and the default `OpentelemetryLog`, give explicit `Record::key_values()` precedence over colliding `Diagnostic` entries. Multi-value outputs such as `Journald` preserve both values. - Nested layouts isolate structured entries under dedicated sub-objects (`attributes` and `context`), whereas flat layouts and protocol sinks emit record metadata and key-values in a single flat namespace; avoid reusing reserved top-level field names such as `timestamp`, `level`, `severity`, `message`, `module`, `module_path`, `file`, `line`, `column`, `position`, or `code.*` when targeting flat sinks. diff --git a/appenders/opentelemetry/README.md b/appenders/opentelemetry/README.md index 8f53f0ea..7ef4c1d1 100644 --- a/appenders/opentelemetry/README.md +++ b/appenders/opentelemetry/README.md @@ -60,12 +60,15 @@ Each `Record` is projected onto an `opentelemetry_sdk::logs::SdkLogRecord`: | `severity_number` / `text` | 1-to-1 mapping across all 24 `Level` variants (`Trace`..=`Fatal4` -> `Severity::Trace`..=`Severity::Fatal4`) and `Level::name()`. | | `body` | `AnyValue::String` from `Record::payload()` (omitted when empty), or custom `AnyValue` via `MakeBody` (such as `MakeBodyLayout`). | | `trace_context` | Extracted from `Diagnostic` `("trace_id", "span_id")` (32- and 16-digit non-zero hex) and optional boolean `"sampled"`. | -| `attributes` | Present `code.function.name` (`module_path`), `code.file.path`, `code.line.number`, `code.column.number`, `Record::key_values()`, and remaining `Diagnostic` entries. | +| `attributes` | Present `code.function.name` (`module_path`), `code.file.path`, `code.line.number`, `code.column.number`, remaining `Diagnostic` entries, and `Record::key_values()`. | | `OpentelemetryLog` method | Effect | | :-------------------------- | :------------------------------------------------------------------------------------------------------- | | `new(scope, provider)` | Emits records through `provider` (`SdkLoggerProvider`) under `scope` (`InstrumentationScope`). | | `with_make_body(make_body)` | Overrides how `SdkLogRecord` bodies (`AnyValue`) are constructed via a custom `MakeBody` implementation. | +| `allow_duplicate_keys()` | Passes repeated top-level attribute keys to the SDK in source location, diagnostic, then record order. | + +By default, explicit record fields override diagnostics, diagnostics override source location, and the last value wins within each source. With `allow_duplicate_keys()`, callers using OTLP must ensure that their keys are unique. Receivers may handle duplicates unpredictably. See the [OpenTelemetry attribute collection specification](https://opentelemetry.io/docs/specs/otel/common/#attribute-collections). `opentelemetry` and `opentelemetry_sdk` are re-exported at `logforth_append_opentelemetry::{opentelemetry, opentelemetry_sdk}` so callers do not need direct Cargo dependencies solely to name SDK traits or types. diff --git a/appenders/opentelemetry/src/lib.rs b/appenders/opentelemetry/src/lib.rs index 60544473..a4692ee5 100644 --- a/appenders/opentelemetry/src/lib.rs +++ b/appenders/opentelemetry/src/lib.rs @@ -25,8 +25,8 @@ //! custom bytes/values produced by [`MakeBody`] (such as [`MakeBodyLayout`]); //! - source location attributes, when present, use `code.function.name` ([`Record::module_path`]), //! `code.file.path`, `code.line.number`, and `code.column.number`; -//! - [`Record::key_values`] entries followed by [`Diagnostic`] entries unused by the trace context -//! are mapped to typed [`AnyValue`] attributes in order; +//! - attribute keys are unique by default. On collision, explicit [`Record::key_values`] override +//! [`Diagnostic`] entries, which override source location. Within a source the last value wins; //! - [`Diagnostic`] `"trace_id"` (32-digit non-zero hex) and `"span_id"` (16-digit non-zero hex), //! plus optional boolean `"sampled"`, populate [`LogRecord::set_trace_context`]. //! @@ -45,6 +45,7 @@ pub extern crate opentelemetry; pub extern crate opentelemetry_sdk; +use std::collections::BTreeSet; use std::collections::HashMap; use std::fmt; use std::sync::Arc; @@ -101,6 +102,7 @@ const KEY_SAMPLED: &str = "sampled"; #[derive(Debug)] pub struct OpentelemetryLog { make_body: Option>, + allow_duplicate_keys: bool, logger: opentelemetry_sdk::logs::SdkLogger, provider: SdkLoggerProvider, } @@ -129,6 +131,7 @@ impl OpentelemetryLog { let logger = provider.logger_with_scope(scope); OpentelemetryLog { make_body: None, + allow_duplicate_keys: false, logger, provider, } @@ -158,6 +161,16 @@ impl OpentelemetryLog { self.make_body = Some(make_body.into()); self } + + /// Passes top-level log attributes to the SDK in source location, diagnostic, then record + /// order, including repeated keys. + /// + /// Callers using OTLP must ensure that their attribute keys are unique. Receivers may + /// handle duplicates unpredictably. + pub fn allow_duplicate_keys(mut self) -> Self { + self.allow_duplicate_keys = true; + self + } } impl Append for OpentelemetryLog { @@ -181,34 +194,40 @@ impl Append for OpentelemetryLog { } } + let trace_context = extract_trace_context(diags)?; + if let Some((trace_id, span_id, flags)) = trace_context { + log_record.set_trace_context(trace_id, span_id, flags); + } + + let mut attributes = Vec::new(); + let mut add_attribute = |key: Key, value: AnyValue| { + if self.allow_duplicate_keys { + log_record.add_attribute(key, value); + } else { + attributes.push((key, Some(value))); + } + }; + if let Some(module_path) = record.module_path_static() { - log_record.add_attribute(ATTR_CODE_FUNCTION_NAME, module_path); + add_attribute(ATTR_CODE_FUNCTION_NAME.into(), module_path.into()); } else if let Some(module_path) = record.module_path() { - log_record.add_attribute(ATTR_CODE_FUNCTION_NAME, module_path.to_owned()); + add_attribute( + ATTR_CODE_FUNCTION_NAME.into(), + module_path.to_owned().into(), + ); } - if let Some(file) = record.file_static() { - log_record.add_attribute(ATTR_CODE_FILE_PATH, file); + add_attribute(ATTR_CODE_FILE_PATH.into(), file.into()); } else if let Some(file) = record.file() { - log_record.add_attribute(ATTR_CODE_FILE_PATH, file.to_owned()); + add_attribute(ATTR_CODE_FILE_PATH.into(), file.to_owned().into()); } - if let Some(line) = record.line() { - log_record.add_attribute(ATTR_CODE_LINE_NUMBER, line); + add_attribute(ATTR_CODE_LINE_NUMBER.into(), line.into()); } - if let Some(column) = record.column() { - log_record.add_attribute(ATTR_CODE_COLUMN_NUMBER, column); + add_attribute(ATTR_CODE_COLUMN_NUMBER.into(), column.into()); } - let trace_context = extract_trace_context(diags)?; - if let Some((trace_id, span_id, flags)) = trace_context { - log_record.set_trace_context(trace_id, span_id, flags); - } - - for (key, value) in record.key_values() { - log_record.add_attribute(key_to_key(key), value_to_any_value(value)); - } diags.visit(&mut |key: KeyView, value: ValueView| { let consumed = match key.as_str() { KEY_TRACE_ID | KEY_SPAN_ID => trace_context.is_some(), @@ -218,9 +237,24 @@ impl Append for OpentelemetryLog { if consumed { return Ok(()); } - log_record.add_attribute(key_to_key(key), value_to_any_value(value)); + add_attribute(key_to_key(key), value_to_any_value(value)); Ok(()) })?; + for (key, value) in record.key_values() { + add_attribute(key_to_key(key), value_to_any_value(value)); + } + // Visiting backwards keeps the last value without reordering the surviving attributes. + let mut seen = BTreeSet::new(); + for (key, value) in attributes.iter_mut().rev() { + if !seen.insert(key.as_str()) { + *value = None; + } + } + for (key, value) in attributes { + if let Some(value) = value { + log_record.add_attribute(key, value); + } + } self.logger.emit(log_record); Ok(()) diff --git a/tests-integration/tests/append_test/opentelemetry.rs b/tests-integration/tests/append_test/opentelemetry.rs index a287bac8..dab9d5af 100644 --- a/tests-integration/tests/append_test/opentelemetry.rs +++ b/tests-integration/tests/append_test/opentelemetry.rs @@ -224,6 +224,7 @@ fn opentelemetry_appender_encodes_typed_attributes_and_diagnostics() { assert_eq!( attrs, vec![ + ("region".to_owned(), AnyValue::from("us-east-1")), ("env".to_owned(), AnyValue::from("from-record")), ("flag".to_owned(), AnyValue::Boolean(true)), ("small_u64".to_owned(), AnyValue::Int(99)), @@ -248,8 +249,56 @@ fn opentelemetry_appender_encodes_typed_attributes_and_diagnostics() { AnyValue::ListAny(Box::new(vec![AnyValue::Int(1), AnyValue::from("two")])) ), ("map".to_owned(), AnyValue::Map(Box::new(expected_map))), - ("env".to_owned(), AnyValue::from("from-diag")), - ("region".to_owned(), AnyValue::from("us-east-1")), + ] + ); +} + +#[test] +fn opentelemetry_attribute_collisions_across_sources() { + let exporter = InMemoryLogExporter::default(); + let provider = SdkLoggerProvider::builder() + .with_simple_exporter(exporter.clone()) + .build(); + let appender = || { + OpentelemetryLog::new( + InstrumentationScope::builder("attribute-collisions").build(), + provider.clone(), + ) + }; + let diags = [ + StaticDiagnostic::new([("code.column.number", 20), ("code.line.number", 10)]), + StaticDiagnostic::new([("code.column.number", 21)]), + ]; + let fields = [ + (kv::Key::new("code.line.number"), Value::i64(30)), + (kv::Key::new("code.line.number"), Value::i64(31)), + ]; + let record = RecordBuilder::new() + .line(Some(1)) + .column(Some(2)) + .key_values(&fields[..]) + .build(); + + appender().append(&record, &diags).unwrap(); + appender() + .allow_duplicate_keys() + .append(&record, &diags) + .unwrap(); + + let logs = exporter.get_emitted_logs().unwrap(); + let line = |n| ("code.line.number".to_owned(), AnyValue::Int(n)); + let column = |n| ("code.column.number".to_owned(), AnyValue::Int(n)); + assert_eq!(attrs_vec(&logs[0].record), [column(21), line(31)]); + assert_eq!( + attrs_vec(&logs[1].record), + [ + line(1), + column(2), + column(20), + line(10), + column(21), + line(30), + line(31) ] ); } @@ -338,7 +387,6 @@ fn opentelemetry_appender_extracts_trace_context_and_preserves_incomplete_or_inv assert_eq!( attrs_vec(&log), [ - ("sampled".to_owned(), AnyValue::Boolean(false)), ("sampled".to_owned(), AnyValue::from("unknown")), ("trace_sampled".to_owned(), AnyValue::Boolean(true)), ] @@ -359,7 +407,6 @@ fn opentelemetry_appender_extracts_trace_context_and_preserves_incomplete_or_inv attrs_vec(&log), [ attributes[1].clone(), - attributes[0].clone(), ("trace_id".to_owned(), AnyValue::from("invalid")), ] ); From bc9f3fa94ac61650072956dd5e7436ac7ed46e5b Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 3 Dec 2026 01:56:46 +0800 Subject: [PATCH 2/2] perf(append-opentelemetry): avoid extra allocations on default attribute dedup Skip temporary allocations when no diagnostic or record attributes remain, deduplicate up to 16 attributes in place without allocating a set, switch larger attribute collections to a pre-sized `HashSet`, pre-size nested list and map conversions, cover the `> 16` collision boundary, and align documentation across `OpentelemetryLog`, `README.md`, `DESIGN.md`, and `CHANGELOG.md`. Signed-off-by: tison --- CHANGELOG.md | 2 +- DESIGN.md | 2 +- appenders/opentelemetry/README.md | 4 +- appenders/opentelemetry/src/lib.rs | 214 ++++++++++++------ .../tests/append_test/opentelemetry.rs | 15 ++ 5 files changed, 159 insertions(+), 78 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bcf10144..33b87087 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -112,7 +112,7 @@ All significant changes to this project will be documented in this file. * `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging` now gives explicit `Record` key-values precedence over colliding `Diagnostic` entries. * `Async` in `logforth-append-async` now flushes inner appenders on `Drop` after draining queued records, isolates panics in inner appenders and `ErrorSink` during `append`, `flush`, and shutdown instead of terminating the worker thread or panicking in `Drop`, and waits for full bounded queues to drain during `flush` under `overflow_drop_incoming`. * `File` in `logforth-append-file` now opens segment files in append mode so external truncation does not leave NUL holes, and no longer panics or truncates timestamps and file sizes on matching prefix/suffix edge cases, out-of-range timestamps, or 32-bit targets. -* `OpentelemetryLog` in `logforth-append-opentelemetry` now emits unique log attribute keys by default, with explicit record fields overriding diagnostics and diagnostics overriding source location. Use `allow_duplicate_keys()` to pass repeated attributes to the SDK. +* `OpentelemetryLog` in `logforth-append-opentelemetry` now deduplicates top-level log attribute keys by default (giving explicit `Record` key-values precedence over `Diagnostic` entries and `Diagnostic` entries precedence over `code.*` source location attributes); call `OpentelemetryLog::allow_duplicate_keys` to forward repeated keys unmodified. * `OpentelemetryLog` in `logforth-append-opentelemetry` now sets `LogRecord::set_timestamp` from `Record::time()` instead of overwriting the event timestamp with `SystemTime::now()`. * `SocketSyslog` in `logforth-append-syslog` now formats syslog header timestamps from `Record::time()` instead of overwriting them with `SystemTime::now()`, and omits the RFC 3164 `HOSTNAME` token on local Unix socket builders (`SocketSyslogBuilder::{unix, unix_datagram, unix_stream}`) so `systemd-journald` and `rsyslog` parse `TAG[PID]` accurately. * `ThreadLocalDiagnostic` and `TaskLocalDiagnostic` no longer panic when logging during thread-local teardown, degrading to an empty context instead. diff --git a/DESIGN.md b/DESIGN.md index e8057822..6018882c 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -71,5 +71,5 @@ Logforth separates three concerns into distinct primitives: ### Precedence and Reserved Top-Level Fields -- Structured key-values and diagnostic entries are visited in order. Outputs that require unique keys, including `GoogleCloudLoggingLayout` and the default `OpentelemetryLog`, give explicit `Record::key_values()` precedence over colliding `Diagnostic` entries. Multi-value outputs such as `Journald` preserve both values. +- Structured key-values and diagnostic entries are visited in source order: targets that enforce unique keys in a shared namespace (such as `GoogleCloudLoggingLayout` and `OpentelemetryLog` by default) resolve collisions using last-entry-wins precedence with explicit `Record::key_values()` overriding `Diagnostic` entries, whereas stream layouts and multi-value sinks (such as `TextLayout`, `LogfmtLayout`, `JsonLayout`, and `Journald`) emit entries without cross-source deduplication. - Nested layouts isolate structured entries under dedicated sub-objects (`attributes` and `context`), whereas flat layouts and protocol sinks emit record metadata and key-values in a single flat namespace; avoid reusing reserved top-level field names such as `timestamp`, `level`, `severity`, `message`, `module`, `module_path`, `file`, `line`, `column`, `position`, or `code.*` when targeting flat sinks. diff --git a/appenders/opentelemetry/README.md b/appenders/opentelemetry/README.md index 7ef4c1d1..c1c6da0a 100644 --- a/appenders/opentelemetry/README.md +++ b/appenders/opentelemetry/README.md @@ -66,9 +66,9 @@ Each `Record` is projected onto an `opentelemetry_sdk::logs::SdkLogRecord`: | :-------------------------- | :------------------------------------------------------------------------------------------------------- | | `new(scope, provider)` | Emits records through `provider` (`SdkLoggerProvider`) under `scope` (`InstrumentationScope`). | | `with_make_body(make_body)` | Overrides how `SdkLogRecord` bodies (`AnyValue`) are constructed via a custom `MakeBody` implementation. | -| `allow_duplicate_keys()` | Passes repeated top-level attribute keys to the SDK in source location, diagnostic, then record order. | +| `allow_duplicate_keys()` | Forwards attributes in source location, diagnostic, then record order without deduplicating keys. | -By default, explicit record fields override diagnostics, diagnostics override source location, and the last value wins within each source. With `allow_duplicate_keys()`, callers using OTLP must ensure that their keys are unique. Receivers may handle duplicates unpredictably. See the [OpenTelemetry attribute collection specification](https://opentelemetry.io/docs/specs/otel/common/#attribute-collections). +By default, `OpentelemetryLog` enforces unique top-level attribute keys per the [OpenTelemetry attribute collection specification](https://opentelemetry.io/docs/specs/otel/common/#attribute-collections): explicit `Record::key_values()` override colliding `Diagnostic` entries, `Diagnostic` entries override `code.*` source location attributes, and the last entry wins within each source while preserving relative order. Because many receivers handle duplicate attribute keys unpredictably, callers enabling `allow_duplicate_keys()` are responsible for ensuring exported keys are unique unless targeting a custom processor designed for repeated keys. `opentelemetry` and `opentelemetry_sdk` are re-exported at `logforth_append_opentelemetry::{opentelemetry, opentelemetry_sdk}` so callers do not need direct Cargo dependencies solely to name SDK traits or types. diff --git a/appenders/opentelemetry/src/lib.rs b/appenders/opentelemetry/src/lib.rs index 9b4bdd24..6352376a 100644 --- a/appenders/opentelemetry/src/lib.rs +++ b/appenders/opentelemetry/src/lib.rs @@ -14,21 +14,27 @@ //! OpenTelemetry Logs integration for Logforth. //! -//! [`OpentelemetryLog`] converts each Logforth [`Record`] into an OpenTelemetry -//! [`SdkLogRecord`](opentelemetry_sdk::logs::SdkLogRecord) and exports records through an -//! [`SdkLoggerProvider`]: -//! - `timestamp` is set from [`Record::time`] (event creation time) and `observed_timestamp` is set -//! from [`SystemTime::now`] when appended; -//! - `severity_number` and `severity_text` map 1-to-1 across all 24 OpenTelemetry-aligned [`Level`] -//! variants; -//! - `body` defaults to the formatted [`Record::payload`] string (omitted when empty), or uses -//! custom bytes/values produced by [`MakeBody`] (such as [`MakeBodyLayout`]); -//! - source location attributes, when present, use `code.function.name` ([`Record::module_path`]), -//! `code.file.path`, `code.line.number`, and `code.column.number`; -//! - attribute keys are unique by default. On collision, explicit [`Record::key_values`] override -//! [`Diagnostic`] entries, which override source location. Within a source the last value wins; -//! - [`Diagnostic`] `"trace_id"` (32-digit non-zero hex) and `"span_id"` (16-digit non-zero hex), -//! plus optional boolean `"sampled"`, populate [`LogRecord::set_trace_context`]. +//! [`OpentelemetryLog`] sends each [`Record`] to its [`SdkLoggerProvider`] as an [`SdkLogRecord`]. +//! +//! - `timestamp` records the event time from [`Record::time`]. `observed_timestamp` records when +//! the appender observes the event. +//! - `severity_number` and `severity_text` carry the OpenTelemetry severity and name for each of +//! the 24 [`Level`] variants. +//! - `body` contains the formatted [`Record::payload`] as a string when nonempty. A custom +//! [`MakeBody`] supplies its own [`AnyValue`], such as the bytes produced by [`MakeBodyLayout`]. +//! - `trace_context` comes from [`Diagnostic`] entries when both `trace_id` and `span_id` are +//! nonzero hexadecimal IDs of 32 and 16 digits respectively. An optional boolean `sampled` sets +//! the trace flags. Unconsumed entries remain available as attributes. +//! - `attributes` begin with the available source location fields (`code.function.name` from +//! [`Record::module_path`], `code.file.path`, `code.line.number`, and `code.column.number`), +//! followed by diagnostic entries and then [`Record::key_values`]. By default only the last +//! occurrence of each key survives, in its original position. +//! [`OpentelemetryLog::allow_duplicate_keys`] retains every occurrence. +//! +//! Attribute values map to typed [`AnyValue`] variants for strings, booleans, bytes, floating-point +//! numbers, and integers that fit in `i64`. Lists and maps convert recursively. Larger integers, +//! characters, and formatted values become strings, and an absent value becomes the string +//! `"null"`. //! //! Build an [`SdkLoggerProvider`] with `with_batch_exporter`, `with_simple_exporter`, or a custom //! [`LogProcessor`](opentelemetry_sdk::logs::LogProcessor). Use [`Resource`](opentelemetry_sdk::Resource) @@ -45,8 +51,8 @@ pub extern crate opentelemetry; pub extern crate opentelemetry_sdk; -use std::collections::BTreeSet; use std::collections::HashMap; +use std::collections::HashSet; use std::fmt; use std::sync::Arc; use std::time::SystemTime; @@ -68,6 +74,7 @@ use opentelemetry::logs::AnyValue; use opentelemetry::logs::LogRecord; use opentelemetry::logs::Logger; use opentelemetry::logs::LoggerProvider; +use opentelemetry_sdk::logs::SdkLogRecord; use opentelemetry_sdk::logs::SdkLogger; use opentelemetry_sdk::logs::SdkLoggerProvider; @@ -163,11 +170,24 @@ impl OpentelemetryLog { self } - /// Passes top-level log attributes to the SDK in source location, diagnostic, then record - /// order, including repeated keys. + /// Emits every occurrence of each top-level attribute key in source location, diagnostic, + /// then record order instead of keeping only the last occurrence. + /// + /// OpenTelemetry requires unique attribute keys by default, and many receivers handle + /// duplicate keys unpredictably; callers enabling this option are responsible for ensuring + /// exported keys are unique unless targeting a processor designed for repeated keys. + /// + /// # Examples + /// + /// ``` + /// use logforth_append_opentelemetry::OpentelemetryLog; + /// use opentelemetry::InstrumentationScope; + /// use opentelemetry_sdk::logs::SdkLoggerProvider; /// - /// Callers using OTLP must ensure that their attribute keys are unique. Receivers may - /// handle duplicates unpredictably. + /// let scope = InstrumentationScope::builder("billing").build(); + /// let provider = SdkLoggerProvider::builder().build(); + /// let appender = OpentelemetryLog::new(scope, provider).allow_duplicate_keys(); + /// ``` pub fn allow_duplicate_keys(mut self) -> Self { self.allow_duplicate_keys = true; self @@ -200,60 +220,68 @@ impl Append for OpentelemetryLog { log_record.set_trace_context(trace_id, span_id, flags); } - let mut attributes = Vec::new(); - let mut add_attribute = |key: Key, value: AnyValue| { - if self.allow_duplicate_keys { - log_record.add_attribute(key, value); - } else { - attributes.push((key, Some(value))); - } + let consumed = |key: &str| match key { + KEY_TRACE_ID | KEY_SPAN_ID => trace_context.is_some(), + KEY_SAMPLED => matches!(trace_context, Some((_, _, Some(_)))), + _ => false, }; - - if let Some(module_path) = record.module_path_static() { - add_attribute(ATTR_CODE_FUNCTION_NAME.into(), module_path.into()); - } else if let Some(module_path) = record.module_path() { - add_attribute( - ATTR_CODE_FUNCTION_NAME.into(), - module_path.to_owned().into(), - ); - } - if let Some(file) = record.file_static() { - add_attribute(ATTR_CODE_FILE_PATH.into(), file.into()); - } else if let Some(file) = record.file() { - add_attribute(ATTR_CODE_FILE_PATH.into(), file.to_owned().into()); - } - if let Some(line) = record.line() { - add_attribute(ATTR_CODE_LINE_NUMBER.into(), line.into()); - } - if let Some(column) = record.column() { - add_attribute(ATTR_CODE_COLUMN_NUMBER.into(), column.into()); - } - - diags.visit(&mut |key: KeyView, value: ValueView| { - let consumed = match key.as_str() { - KEY_TRACE_ID | KEY_SPAN_ID => trace_context.is_some(), - KEY_SAMPLED => matches!(trace_context, Some((_, _, Some(_)))), - _ => false, - }; - if consumed { - return Ok(()); + if self.allow_duplicate_keys { + add_source_location(&mut log_record, record, |_| true); + diags.visit(&mut |key: KeyView, value: ValueView| { + if !consumed(key.as_str()) { + log_record.add_attribute(key_to_key(key), value_to_any_value(value)); + } + Ok(()) + })?; + for (key, value) in record.key_values() { + log_record.add_attribute(key_to_key(key), value_to_any_value(value)); } - add_attribute(key_to_key(key), value_to_any_value(value)); - Ok(()) - })?; - for (key, value) in record.key_values() { - add_attribute(key_to_key(key), value_to_any_value(value)); - } - // Visiting backwards keeps the last value without reordering the surviving attributes. - let mut seen = BTreeSet::new(); - for (key, value) in attributes.iter_mut().rev() { - if !seen.insert(key.as_str()) { - *value = None; + } else { + let mut attributes: Vec<(Key, Option)> = Vec::new(); + diags.visit(&mut |key: KeyView, value: ValueView| { + if !consumed(key.as_str()) { + attributes.push((key_to_key(key), Some(value_to_any_value(value)))); + } + Ok(()) + })?; + let kvs = record.key_values(); + if !kvs.is_empty() { + attributes.reserve(kvs.len()); } - } - for (key, value) in attributes { - if let Some(value) = value { - log_record.add_attribute(key, value); + for (key, value) in kvs { + attributes.push((key_to_key(key), Some(value_to_any_value(value)))); + } + + if attributes.is_empty() { + add_source_location(&mut log_record, record, |_| true); + } else if attributes.len() <= 16 { + for i in (0..attributes.len()).rev() { + let key = attributes[i].0.as_str(); + if attributes[i + 1..] + .iter() + .any(|(k, v)| v.is_some() && k.as_str() == key) + { + attributes[i].1 = None; + } + } + add_source_location(&mut log_record, record, |attr| { + !attributes + .iter() + .any(|(k, v)| v.is_some() && k.as_str() == attr) + }); + } else { + let mut seen = HashSet::with_capacity(attributes.len()); + for (key, value) in attributes.iter_mut().rev() { + if !seen.insert(key.as_str()) { + *value = None; + } + } + add_source_location(&mut log_record, record, |attr| !seen.contains(attr)); + } + for (key, value) in attributes { + if let Some(value) = value { + log_record.add_attribute(key, value); + } } } @@ -268,6 +296,44 @@ impl Append for OpentelemetryLog { } } +fn add_source_location( + log_record: &mut SdkLogRecord, + record: &Record, + mut keep: impl FnMut(&str) -> bool, +) { + if let Some(module_path) = record.module_path_static() { + if keep(ATTR_CODE_FUNCTION_NAME) { + log_record.add_attribute(ATTR_CODE_FUNCTION_NAME, module_path); + } + } else if let Some(module_path) = record.module_path() + && keep(ATTR_CODE_FUNCTION_NAME) + { + log_record.add_attribute(ATTR_CODE_FUNCTION_NAME, module_path.to_owned()); + } + + if let Some(file) = record.file_static() { + if keep(ATTR_CODE_FILE_PATH) { + log_record.add_attribute(ATTR_CODE_FILE_PATH, file); + } + } else if let Some(file) = record.file() + && keep(ATTR_CODE_FILE_PATH) + { + log_record.add_attribute(ATTR_CODE_FILE_PATH, file.to_owned()); + } + + if let Some(line) = record.line() + && keep(ATTR_CODE_LINE_NUMBER) + { + log_record.add_attribute(ATTR_CODE_LINE_NUMBER, line); + } + + if let Some(column) = record.column() + && keep(ATTR_CODE_COLUMN_NUMBER) + { + log_record.add_attribute(ATTR_CODE_COLUMN_NUMBER, column); + } +} + fn log_level_to_otel_severity(level: Level) -> opentelemetry::logs::Severity { match level { Level::Trace => opentelemetry::logs::Severity::Trace, @@ -297,7 +363,7 @@ fn log_level_to_otel_severity(level: Level) -> opentelemetry::logs::Severity { } } -/// A constructor for [`SdkLogRecord`](opentelemetry_sdk::logs::SdkLogRecord) bodies as OpenTelemetry [`AnyValue`] values. +/// A constructor for [`SdkLogRecord`] bodies as OpenTelemetry [`AnyValue`] values. /// /// Implement [`MakeBody`] directly to emit a UTF-8 [`AnyValue::String`] from a [`Layout`] or to /// build a structured [`AnyValue::Map`] or [`AnyValue::ListAny`]. [`MakeBodyLayout`] emits @@ -475,14 +541,14 @@ fn value_to_any_value(value: ValueView) -> AnyValue { } } ValueView::List(v) => { - let mut l = Vec::new(); + let mut l = Vec::with_capacity(v.len()); for item in v.iter() { l.push(value_to_any_value(item)); } AnyValue::ListAny(Box::new(l)) } ValueView::Map(v) => { - let mut m = HashMap::new(); + let mut m = HashMap::with_capacity(v.len()); for (k, v) in v.iter() { m.insert(key_to_key(k), value_to_any_value(v)); } diff --git a/tests-integration/tests/append_test/opentelemetry.rs b/tests-integration/tests/append_test/opentelemetry.rs index 4b8c2230..a9723079 100644 --- a/tests-integration/tests/append_test/opentelemetry.rs +++ b/tests-integration/tests/append_test/opentelemetry.rs @@ -308,6 +308,21 @@ fn opentelemetry_attribute_collisions_across_sources() { line(31) ] ); + + exporter.reset(); + let mut fields = Vec::new(); + for i in 0..20i64 { + fields.push((KeyOwned::new(format!("extra_{i}")), ValueOwned::from(i))); + } + fields.push((KeyOwned::new("code.line.number"), ValueOwned::from(31i64))); + let record = record.to_builder().key_values(&fields[..]).build(); + appender().append(&record, &diags).unwrap(); + + let logs = exporter.get_emitted_logs().unwrap(); + let mut expected = vec![column(21)]; + expected.extend((0..20).map(|i| (format!("extra_{i}"), AnyValue::Int(i)))); + expected.push(line(31)); + assert_eq!(attrs_vec(&logs[0].record), expected); } #[test]