Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.
2 changes: 1 addition & 1 deletion DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.
5 changes: 4 additions & 1 deletion appenders/opentelemetry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()` | Forwards attributes in source location, diagnostic, then record order without deduplicating keys. |

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.

Expand Down
206 changes: 153 additions & 53 deletions appenders/opentelemetry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`;
//! - [`Record::key_values`] entries followed by [`Diagnostic`] entries unused by the trace context
//! are mapped to typed [`AnyValue`] attributes in order;
//! - [`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)
Expand All @@ -46,6 +52,7 @@ pub extern crate opentelemetry;
pub extern crate opentelemetry_sdk;

use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt;
use std::sync::Arc;
use std::time::SystemTime;
Expand All @@ -67,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;

Expand Down Expand Up @@ -104,6 +112,7 @@ pub struct OpentelemetryLog {
logger: SdkLogger,
provider: SdkLoggerProvider,
make_body: Option<Box<dyn MakeBody>>,
allow_duplicate_keys: bool,
}

impl OpentelemetryLog {
Expand All @@ -129,9 +138,10 @@ impl OpentelemetryLog {
pub fn new(scope: InstrumentationScope, provider: SdkLoggerProvider) -> Self {
let logger = provider.logger_with_scope(scope);
OpentelemetryLog {
make_body: None,
logger,
provider,
make_body: None,
allow_duplicate_keys: false,
}
}

Expand Down Expand Up @@ -159,6 +169,29 @@ impl OpentelemetryLog {
self.make_body = Some(make_body.into());
self
}

/// 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;
///
/// 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
}
}

impl Append for OpentelemetryLog {
Expand All @@ -182,46 +215,75 @@ impl Append for OpentelemetryLog {
}
}

if let Some(module_path) = record.module_path_static() {
log_record.add_attribute(ATTR_CODE_FUNCTION_NAME, module_path);
} else if let Some(module_path) = record.module_path() {
log_record.add_attribute(ATTR_CODE_FUNCTION_NAME, module_path.to_owned());
}

if let Some(file) = record.file_static() {
log_record.add_attribute(ATTR_CODE_FILE_PATH, file);
} else if let Some(file) = record.file() {
log_record.add_attribute(ATTR_CODE_FILE_PATH, file.to_owned());
}

if let Some(line) = record.line() {
log_record.add_attribute(ATTR_CODE_LINE_NUMBER, line);
}

if let Some(column) = record.column() {
log_record.add_attribute(ATTR_CODE_COLUMN_NUMBER, column);
}

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(),
KEY_SAMPLED => matches!(trace_context, Some((_, _, Some(_)))),
_ => false,
};
if consumed {
return Ok(());
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 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));
}
} else {
let mut attributes: Vec<(Key, Option<AnyValue>)> = 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 kvs {
attributes.push((key_to_key(key), Some(value_to_any_value(value))));
}
log_record.add_attribute(key_to_key(key), value_to_any_value(value));
Ok(())
})?;

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);
}
}
}

self.logger.emit(log_record);
Ok(())
Expand All @@ -234,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,
Expand Down Expand Up @@ -263,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
Expand Down Expand Up @@ -441,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));
}
Expand Down
Loading
Loading