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
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ All significant changes to this project will be documented in this file.
* `File` in `logforth-append-file` now writes directly to target segment files instead of writing to an unnumbered active file and shifting reverse-numbered archives on rollover. Unrotated output remains `<filename>[.<suffix>]`, time-only rotation writes `<filename>.<period>[.<suffix>]`, and size rotation numbers segments in ascending order from `1` (oldest) as `<filename>[.<period>].<seq>[.<suffix>]`; `max_log_files` counts the active file toward the retention limit, and files created under the previous naming scheme are ignored or ordered by ascending sequence number until moved or removed.
* `FileBuilder::rollover_size` in `logforth-append-file` now takes `NonZeroU64` instead of `NonZeroUsize` and rotates before a write would exceed the size limit rather than after; update callers passing `NonZeroUsize` to pass `NonZeroU64`.
* `FileBuilder::build` in `logforth-append-file` now returns `Err` when `filename` or `filename_suffix` is empty, `.` or `..`, or contains path separators or NUL bytes.
* Align `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging` with Google Cloud Structured Logging: map all 24 `Level` severities to canonical `LogSeverity` strings (`DEBUG`, `INFO`, `NOTICE`, `WARNING`, `ERROR`, `CRITICAL`, `ALERT`, and `EMERGENCY`), format `logging.googleapis.com/labels` values as JSON strings, and omit `logging.googleapis.com/sourceLocation` when `file`, `line`, and `module_path` are all unset.
* Align `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging` with Google Cloud Structured Logging: map all 24 `Level` severities to canonical `LogSeverity` strings (`DEBUG`, `INFO`, `NOTICE`, `WARNING`, `ERROR`, `CRITICAL`, `ALERT`, and `EMERGENCY`), format `logging.googleapis.com/labels` values as JSON strings, omit `logging.googleapis.com/sourceLocation` when `file`, `line`, and `module_path` are all unset, and extract Cloud Trace correlation fields only from `Diagnostic` `("trace_id", "span_id", "sampled")` entries (removing the `"trace_sampled"` diagnostic alias and keeping `Record::key_values()` entries as ordinary payload or label fields).
* Replace `AsyncBuilder::buffered_lines_limit(Option<usize>)` with `AsyncBuilder::max_buffered_records(NonZeroUsize)` and change `AsyncBuilder::build` to return `Result<Async, Error>` in `logforth-append-async`, returning `Err` instead of panicking when `thread_name` contains NUL bytes or OS thread creation fails; pass a `NonZeroUsize` limit when bounding buffered records (omit `max_buffered_records` for unbounded buffering) and handle the `Result` from `build`.
* Remove the redundant `"timestamp"` event property (and `jiff` dependency) from `FastraceEvent` in `logforth-append-fastrace` and require an active sampled `SpanContext::current_local_parent()` before recording events (skipping parentless `LocalCollector::start()` scopes); read event timestamps from `fastrace::collector::EventRecord::timestamp_unix_ns` instead.
* Broaden `Journald::with_syslog_identifier` in `logforth-append-journald` from `String` to `impl Into<String>`; pass string literals directly without `.into()` where type inference would otherwise be ambiguous.
Expand All @@ -72,7 +72,7 @@ All significant changes to this project will be documented in this file.
* Add `ThreadLocalDiagnostic::scope` and `ThreadLocalDiagnosticGuard` in `logforth-core` for `!Send` RAII scoped thread-local diagnostics that restore shadowed entries on drop.
* Add `kv::LogValue`, `Value::{owned, to_owned}`, `Key::{as_str, to_owned}`, `KeyOwned::as_str`, `DebugValue::new`, `DisplayValue::new`, `KeyView::to_static_str`, and `ValueView::{is_none, to_bytes}` in `logforth-core`, and implement `From` on `kv::{KeyOwned, ValueOwned}` across scalars (including `NonZero*` integers), strings, byte slices, `Option<T>`, and borrowed `kv::{Key, KeyView, Value, ValueView}`.
* Add `TextLayout::{no_timestamp, no_module_path, no_file}` in `logforth-layout-text` to omit the timestamp, module path, or source filename and line number, add `.utc()` and `.precision(u8)` across `TextLayout`, `LogfmtLayout`, and `JsonLayout` for zero-allocation RFC 3339 timestamp formatting, and omit unset location segments in `PlainTextLayout`, `TextLayout`, `LogfmtLayout`, and `JsonLayout` instead of formatting empty or `0` placeholders.
* Extract `"trace_id"`, `"span_id"`, and optional boolean `"sampled"` / `"trace_sampled"` entries from `Record::key_values()` and `Diagnostic` into `LogRecord::set_trace_context` in `logforth-append-opentelemetry`, giving explicit record key-values precedence over diagnostics.
* Extract valid `Diagnostic` `("trace_id", "span_id")` pairs and optional boolean `"sampled"` flags into `LogRecord::set_trace_context` in `logforth-append-opentelemetry`.
* Add `Journald::{from_socket_path, socket_path}` in `logforth-append-journald`.
* Add the standalone `#![no_std]` (`alloc`) `logforth-logfmt` crate providing a zero-dependency `logfmt` `Encoder` and zero-copy `Decoder`, and back `LogfmtLayout` in `logforth-layout-logfmt` with it.
* Add the standalone `logforth-syslog` crate providing RFC 3164 and RFC 5424 formatters (`SyslogContext`, `SdElement`, `SdParam`, `format_rfc3164`, `format_rfc5424`), datagram and reconnectable stream senders (`UdpSender`, `TcpSender`, `TcpTlsSender`, `UnixDatagramSender`, `UnixStreamSender`, `Sender`, `Framing`), and a Unix POSIX `<syslog.h>` backend (`posix::{LogOptions, openlog, syslog, closelog}`), and add `PosixSyslog` / `PosixSyslogBuilder` (`cfg(unix)`), `{PosixSyslogOptions, posix_openlog, posix_closelog}` (`cfg(unix)`), `SocketSyslogBuilder::{udp_socket, framing, timezone}`, and `logforth::append::PosixSyslog` in `logforth-append-syslog` and `logforth`.
Expand Down
11 changes: 5 additions & 6 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,11 @@ Logforth separates three concerns into distinct primitives:

- Unprefixed well-known keys preserve standard field names in external log outputs while coordinating typed context between diagnostics, layouts, and appenders:

| Key | Value Type | Producers | Consumers and Semantics |
| :---------------- | :---------- | :------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| `"trace_id"` | `str` (hex) | `FastraceDiagnostic` | Extracted by `GoogleCloudLoggingLayout` (`logging.googleapis.com/trace`) and `OpentelemetryLog` (`LogRecord::set_trace_context`) |
| `"span_id"` | `str` (hex) | `FastraceDiagnostic` | Extracted by `GoogleCloudLoggingLayout` (`logging.googleapis.com/spanId`) and `OpentelemetryLog` (`LogRecord::set_trace_context`) |
| `"sampled"` | `bool` | `FastraceDiagnostic` | Extracted by `GoogleCloudLoggingLayout` (`logging.googleapis.com/trace_sampled`) and `OpentelemetryLog` (`TraceFlags`) |
| `"trace_sampled"` | `bool` | User diagnostics | Accepted by `GoogleCloudLoggingLayout` and `OpentelemetryLog` alongside `"sampled"` |
| Key | Value Type | Producers | Consumers and Semantics |
| :----------- | :---------- | :------------------- | :-------------------------------------------------------------------------------------------------------------------------------- |
| `"trace_id"` | `str` (hex) | `FastraceDiagnostic` | Extracted by `GoogleCloudLoggingLayout` (`logging.googleapis.com/trace`) and `OpentelemetryLog` (`LogRecord::set_trace_context`) |
| `"span_id"` | `str` (hex) | `FastraceDiagnostic` | Extracted by `GoogleCloudLoggingLayout` (`logging.googleapis.com/spanId`) and `OpentelemetryLog` (`LogRecord::set_trace_context`) |
| `"sampled"` | `bool` | `FastraceDiagnostic` | Extracted by `GoogleCloudLoggingLayout` (`logging.googleapis.com/trace_sampled`) and `OpentelemetryLog` (`TraceFlags`) |

### Precedence and Flat-Format Envelope Fields

Expand Down
18 changes: 9 additions & 9 deletions appenders/opentelemetry/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

Each `Record` is projected onto an `opentelemetry_sdk::logs::SdkLogRecord`:

| `SdkLogRecord` field | Source in Logforth |
| :------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------- |
| `timestamp` | `Record::time()` (event creation time, preserved across `Async` queues and explicit `RecordBuilder::time`). |
| `observed_timestamp` | `SystemTime::now()` captured when `OpentelemetryLog::append` processes the record. |
| `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()`, or custom `AnyValue` produced by `MakeBody` (such as `MakeBodyLayout`). |
| `trace_context` | Extracted when both valid `"trace_id"` (32-hex) and `"span_id"` (16-hex) appear in `Record::key_values()` or `Diagnostic`, plus optional flags. |
| `attributes` | Present `module_path`, `file`, `line`, `column`, followed by typed `Record::key_values()` and unshadowed `Diagnostic` entries. |
| `SdkLogRecord` field | Source in Logforth |
| :------------------------- | :---------------------------------------------------------------------------------------------------------------------------------- |
| `timestamp` | `Record::time()` (event creation time, preserved across `Async` queues and explicit `RecordBuilder::time`). |
| `observed_timestamp` | `SystemTime::now()` captured when `OpentelemetryLog::append` processes the record. |
| `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()`, or custom `AnyValue` produced by `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 `module_path`, `file`, `line`, `column`, followed by typed `Record::key_values()` and unshadowed `Diagnostic` entries. |

| `OpentelemetryLogBuilder` method | Effect |
| :------------------------------- | :-------------------------------------------------------------------------------------------------------------------------- |
Expand All @@ -69,7 +69,7 @@ Each `Record` is projected onto an `opentelemetry_sdk::logs::SdkLogRecord`:

## Trace correlation and operational notes

- **Trace-log correlation**: Pair `OpentelemetryLog` with [`logforth-diagnostic-fastrace`](https://crates.io/crates/logforth-diagnostic-fastrace) (`FastraceDiagnostic`) or any `Diagnostic` / key-value emitting `"trace_id"` and `"span_id"` (plus optional boolean `"sampled"` or `"trace_sampled"`). Valid trace pairs populate `LogRecord::set_trace_context` directly and are omitted from `attributes`; incomplete or non-hex values remain ordinary attributes.
- **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`.

Expand Down
89 changes: 30 additions & 59 deletions appenders/opentelemetry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,8 @@
//! - `module_path`, `file`, `line`, and `column` are attached as attributes when present;
//! - [`Record::key_values`] and [`Diagnostic`] entries are mapped to typed [`AnyValue`] attributes,
//! with explicit record key-values taking precedence over diagnostics;
//! - Well-known `"trace_id"` (32-digit non-zero hex), `"span_id"` (16-digit non-zero hex), and
//! optional boolean `"sampled"` / `"trace_sampled"` entries are extracted into
//! [`LogRecord::set_trace_context`] instead of duplicating them in `attributes`.
//! - [`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`].
//!
//! [`opentelemetry`] and [`opentelemetry_sdk`] are re-exported at the crate root. Call
//! [`Logger::flush`](logforth_core::Logger::flush) before process exit when storing a logger in a
Expand All @@ -50,7 +49,6 @@ use logforth_core::Diagnostic;
use logforth_core::Error;
use logforth_core::Layout;
use logforth_core::append::Append;
use logforth_core::kv::KeyValues;
use logforth_core::kv::KeyView;
use logforth_core::kv::ValueView;
use logforth_core::record::Level;
Expand All @@ -74,7 +72,6 @@ use opentelemetry_sdk::logs::SdkLoggerProvider;
const KEY_TRACE_ID: &str = "trace_id";
const KEY_SPAN_ID: &str = "span_id";
const KEY_SAMPLED: &str = "sampled";
const KEY_TRACE_SAMPLED: &str = "trace_sampled";

/// A builder to configure and create an [`OpentelemetryLog`] appender.
#[derive(Debug)]
Expand Down Expand Up @@ -294,26 +291,22 @@ impl Append for OpentelemetryLog {
log_record.add_attribute("column", column);
}

let kvs = record.key_values();
let has_trace_context =
if let Some((trace_id, span_id, flags)) = extract_trace_context(kvs, diags)? {
log_record.set_trace_context(trace_id, span_id, flags);
true
} else {
false
};
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);
}

kvs.visit(&mut |key: KeyView, value: ValueView| {
if has_trace_context && is_consumed_trace_field(key.as_str(), value) {
return Ok(());
}
let kvs = record.key_values();
for (key, value) in kvs {
log_record.add_attribute(key_to_key(key), value_to_any_value(value));
Ok(())
})?;
}
diags.visit(&mut |key: KeyView, value: ValueView| {
if kvs.get(key.as_str()).is_some()
|| (has_trace_context && is_consumed_trace_field(key.as_str(), value))
{
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 kvs.get(key.as_str()).is_some() || consumed {
return Ok(());
}
log_record.add_attribute(key_to_key(key), value_to_any_value(value));
Expand Down Expand Up @@ -414,52 +407,30 @@ impl MakeBody for MakeBodyLayout {
}

fn extract_trace_context(
kvs: KeyValues<'_>,
diags: &dyn Diagnostic,
) -> Result<Option<(TraceId, SpanId, Option<TraceFlags>)>, Error> {
let mut trace_id = None;
let mut span_id = None;
let mut sampled = None;

let mut visit = |key: KeyView, value: ValueView| {
diags.visit(&mut |key: KeyView, value: ValueView| {
match key.as_str() {
KEY_TRACE_ID => {
trace_id = parse_trace_id(value);
}
KEY_SPAN_ID => {
span_id = parse_span_id(value);
}
KEY_SAMPLED | KEY_TRACE_SAMPLED => {
if let Some(flag) = value.to_bool() {
sampled = Some(flag);
}
}
KEY_TRACE_ID => trace_id = parse_trace_id(value),
KEY_SPAN_ID => span_id = parse_span_id(value),
KEY_SAMPLED => sampled = value.to_bool(),
_ => {}
}
Ok(())
};
diags.visit(&mut visit)?;
kvs.visit(&mut visit)?;

let (Some(trace_id), Some(span_id)) = (trace_id, span_id) else {
return Ok(None);
};
let flags = sampled.map(|flag| {
if flag {
TraceFlags::SAMPLED
} else {
TraceFlags::NOT_SAMPLED
}
});
Ok(Some((trace_id, span_id, flags)))
}

fn is_consumed_trace_field(key: &str, value: ValueView<'_>) -> bool {
match key {
KEY_TRACE_ID | KEY_SPAN_ID => true,
KEY_SAMPLED | KEY_TRACE_SAMPLED => value.to_bool().is_some(),
_ => false,
}
})?;
Ok(trace_id.zip(span_id).map(|(trace_id, span_id)| {
let flags = sampled.map(|flag| {
if flag {
TraceFlags::SAMPLED
} else {
TraceFlags::NOT_SAMPLED
}
});
(trace_id, span_id, flags)
}))
}

fn parse_trace_id(value: ValueView<'_>) -> Option<TraceId> {
Expand Down
Loading
Loading