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
3 changes: 2 additions & 1 deletion appenders/opentelemetry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Each `Record` is projected onto an `opentelemetry_sdk::logs::SdkLogRecord`:
| `new(name, log_exporter)` | Configures the `InstrumentationScope` name and registers `log_exporter` (`impl LogExporter + 'static`) in a batch pipeline. |
| `label(key, value)` | Adds a resource attribute (`opentelemetry::KeyValue`) merged onto `opentelemetry_sdk::Resource::builder()`. |
| `labels(iter)` | Adds multiple `(key, value)` resource attributes. |
| `make_body(make_body)` | Overrides how `SdkLogRecord` bodies are constructed (for example, `MakeBodyLayout::new(JsonLayout::new())`). |
| `make_body(make_body)` | Overrides how `SdkLogRecord` bodies (`AnyValue`) are constructed via a custom `MakeBody` implementation. |
| `build()` | Builds the `OpentelemetryLog` appender. |

`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 All @@ -72,6 +72,7 @@ Each `Record` is projected onto an `opentelemetry_sdk::logs::SdkLogRecord`:
- **Trace-log correlation**: Pair `OpentelemetryLog` with [`logforth-diagnostic-fastrace`](https://crates.io/crates/logforth-diagnostic-fastrace) (`FastraceDiagnostic`) or any `Diagnostic` emitting `"trace_id"` (32-digit non-zero hex) and `"span_id"` (16-digit non-zero hex), plus optional boolean `"sampled"`, to populate `LogRecord::set_trace_context`. Explicit `Record::key_values()` entries always remain ordinary `attributes`.
- **Filter exporter transport targets at `DEBUG` / `TRACE`**: OpenTelemetry's re-entrancy suppression (`Context::enter_telemetry_suppressed_scope`) is thread-local to the SDK batch worker thread, so any `LogExporter` that dispatches network I/O onto dedicated threads or spawned async tasks runs outside that guard. When bridging global `log` output at `DEBUG` or `TRACE`, raise the threshold for your exporter's transport crates to `WARN` (for example, `reqwest` for OTLP/HTTP, or `h2`, `hyper`, `tonic`, and `tower` when `tracing/log` is active) to prevent exporter log amplification.
- **Flush before process exit**: `Append::flush` calls `SdkLoggerProvider::force_flush`, and `Drop` shuts down the provider. Because Rust does not drop `static` items on exit, call `logger.flush()` explicitly before shutdown when storing a `Logger` in a `static`.
- **Custom body construction (`MakeBody` vs. `MakeBodyLayout`)**: `MakeBody` is an open extension trait that can construct any `AnyValue` body (`String`, `Map`, `ListAny`, `Bytes`, or scalar) from `Record` and `Diagnostic`. Because `logforth_core::Layout::format` writes raw `Vec<u8>` bytes, the built-in `MakeBodyLayout` adapter emits `AnyValue::Bytes` (OTLP `bytes_value`, which backends such as Grafana Loki display as Base64); implement `MakeBody` directly when emitting UTF-8 `AnyValue::String` or structured `AnyValue` bodies.

## Documentation

Expand Down
60 changes: 56 additions & 4 deletions appenders/opentelemetry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,14 @@ impl OpentelemetryLogBuilder {
self
}

/// Set the layout for the logs.
/// Configures a custom [`MakeBody`] implementation to construct the [`AnyValue`] body of each
/// log record.
///
/// By default, [`OpentelemetryLog`] formats [`Record::payload`] as [`AnyValue::String`].
/// A [`MakeBody`] implementation can produce any [`AnyValue`] variant (scalars, strings,
/// bytes, lists, or maps) from the [`Record`] and active [`Diagnostic`]s. The built-in
/// [`MakeBodyLayout`] adapter wraps the `Vec<u8>` output of a [`Layout`] as
/// [`AnyValue::Bytes`] (OTLP `bytes_value`).
///
/// # Examples
///
Expand Down Expand Up @@ -359,9 +366,49 @@ fn log_level_to_otel_severity(level: Level) -> opentelemetry::logs::Severity {
}
}

/// A trait for formatting log records into a body that can be sent to OpenTelemetry.
/// Custom strategy for constructing the [`AnyValue`] body of an OpenTelemetry log record.
///
/// Implement [`MakeBody`] to build any [`AnyValue`] variant from a [`Record`] and active
/// [`Diagnostic`]s. The body can hold structured [`AnyValue::Map`] or [`AnyValue::ListAny`]
/// values, custom [`AnyValue::String`] text, scalars, or binary payloads.
///
/// Because [`Layout::format`] writes raw bytes into a `Vec<u8>`, the built-in [`MakeBodyLayout`]
/// adapter emits [`AnyValue::Bytes`] (OTLP `bytes_value`), which backends such as Grafana Loki
/// often display as Base64. To emit the UTF-8 output of a [`Layout`] as [`AnyValue::String`],
/// implement [`MakeBody`] directly as shown in the example.
///
/// # Examples
///
/// ```
/// use logforth_append_opentelemetry::MakeBody;
/// use logforth_append_opentelemetry::OpentelemetryLogBuilder;
/// use logforth_append_opentelemetry::opentelemetry::logs::AnyValue;
/// use logforth_core::Diagnostic;
/// use logforth_core::Error;
/// use logforth_core::Layout;
/// use logforth_core::record::Record;
/// use logforth_layout_json::JsonLayout;
/// use opentelemetry_otlp::LogExporter;
///
/// #[derive(Debug)]
/// struct MakeStringBody<L>(L);
///
/// impl<L: Layout> MakeBody for MakeStringBody<L> {
/// fn create(&self, record: &Record, diags: &dyn Diagnostic) -> Result<AnyValue, Error> {
/// let mut bytes = Vec::new();
/// self.0.format(record, diags, &mut bytes)?;
/// let text = String::from_utf8(bytes)
/// .map_err(|err| Error::new("layout output is not valid UTF-8").with_source(err))?;
/// Ok(AnyValue::String(text.into()))
/// }
/// }
///
/// let log_exporter = LogExporter::builder().with_http().build().unwrap();
/// OpentelemetryLogBuilder::new("my_service", log_exporter)
/// .make_body(MakeStringBody(JsonLayout::default()));
/// ```
pub trait MakeBody: fmt::Debug + Send + Sync + 'static {
/// Creates a log record with optional diagnostics.
/// Constructs the [`AnyValue`] body for `record` with active `diags`.
fn create(&self, record: &Record, diags: &dyn Diagnostic) -> Result<AnyValue, Error>;
}

Expand All @@ -383,7 +430,12 @@ impl<T: MakeBody + ?Sized> MakeBody for &'static T {
}
}

/// Make an OpenTelemetry body with the configured [`Layout`].
/// A [`MakeBody`] adapter that formats records with a [`Layout`] into [`AnyValue::Bytes`].
///
/// [`Layout::format`] writes raw bytes into a `Vec<u8>`. [`MakeBodyLayout`] wraps that buffer
/// directly as [`AnyValue::Bytes`] (OTLP `bytes_value`) without UTF-8 conversion. Backends such
/// as Grafana Loki often display these bytes as Base64. Implement [`MakeBody`] directly to
/// return [`AnyValue::String`] or structured [`AnyValue`] variants.
#[derive(Debug)]
pub struct MakeBodyLayout {
layout: Box<dyn Layout>,
Expand Down
Loading