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
6 changes: 3 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ All significant changes to this project will be documented in this file.
* Upgrade `jiff` from 0.2 to 1.0 in `logforth-append-file`, `logforth-layout-json`, `logforth-layout-logfmt`, and `logforth-layout-text`.
* Replace `colored` with `anstyle` in `logforth-layout-text`: `TextLayout::{fatal_color, error_color, warn_color, info_color, debug_color, trace_color}` now accept `impl Into<anstyle::Color>` (re-exported via `logforth_layout_text::anstyle`), and `TextLayout` emits ANSI colors deterministically without per-record heap allocations unless `TextLayout::no_color` is set.
* Remove `{TextLayout, JsonLayout}::timestamp_format` in `logforth-layout-text` and `logforth-layout-json`; configure timestamps declaratively with `.timezone(tz)` (`+HH:MM`), `.utc()` (`Z`), `.precision(u8)` (default `6` for microseconds), or `TextLayout::no_timestamp()`, and implement `Layout` directly for custom timestamp formats.
* Upgrade `opentelemetry` and `opentelemetry_sdk` from 0.31.0 to 0.33.1 (re-exporting both crates) and remove the mandatory `opentelemetry-otlp` dependency in `logforth-append-opentelemetry`; `OpentelemetryLogBuilder::new` now accepts any `opentelemetry_sdk::logs::LogExporter + 'static` (depend on `opentelemetry-otlp` directly when constructing OTLP exporters).
* Upgrade `opentelemetry` and `opentelemetry_sdk` from 0.32.0 to 0.33.1 (re-exporting both crates) and remove the mandatory `opentelemetry-otlp` dependency in `logforth-append-opentelemetry`; `OpentelemetryLogBuilder::new` now accepts any `opentelemetry_sdk::logs::LogExporter + 'static` (depend on `opentelemetry-otlp` directly when constructing OTLP exporters).
* Remove the `anyhow` dependency from `logforth-core` and redesign `Error`: `Error::new` now accepts `impl Into<Cow<'static, str>>`, `Error::with_source` accepts `impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>` instead of `impl Into<anyhow::Error>` and replaces any existing source instead of panicking, and `Error::{with_context, sources, from_io_error, from_fmt_error}` are removed. Walk `.source()` for causal chains and construct descriptive `Error::new(...).with_source(...)` values at call sites.
* Replace `Trap`, `trap::BestEffortTrap`, `AsyncBuilder::trap`, and `FileBuilder::trap` with `ErrorSink` and `error::{StderrErrorSink, BlackHoleErrorSink}` across `logforth-core`, `logforth`, `logforth-append-async`, and `logforth-append-file`. Configure runtime error handling via `LoggerBuilder::error_sink`, `DispatchBuilder::error_sink`, `AsyncBuilder::error_sink`, or `starter_log::LogStarter::error_sink` instead.
* Replace `Trap`, `trap::BestEffortTrap`, `AsyncBuilder::trap`, and `FileBuilder::trap` with `ErrorSink` and `error::{StderrErrorSink, BlackHoleErrorSink}` across `logforth-core`, `logforth`, `logforth-append-async`, and `logforth-append-file`. Configure runtime error handling via `LoggerBuilder::error_sink`, `AsyncBuilder::error_sink`, or `starter_log::LogStarter::error_sink` instead.
* Replace `&[Box<dyn Diagnostic>]` with `&dyn Diagnostic` across `Filter::filter`, `Layout::format`, `Append::append`, and `MakeBody::create` in `logforth-core`, `logforth`, and peripheral crates, and relax the `'static` supertrait bound on `Diagnostic` to the `Box<dyn Diagnostic>` registration boundary; traverse diagnostics via `diags.visit(&mut visitor)` instead of iterating a slice, and pass `&()` for an empty diagnostic context.
* Change `Layout::format` in `logforth-core` and built-in layouts to append formatted bytes into a caller-supplied `&mut Vec<u8>` and return `Result<(), Error>` instead of `Result<Vec<u8>, Error>`.
* Replace `Filter::{enabled, matches}` and `FilterCriteria` in `logforth-core` with `Filter::{filter_level(&self, level: Level) -> FilterResult, filter(&self, record: &Record, diags: &dyn Diagnostic) -> FilterResult}`, precomputing level bitmasks across `Level::ALL` at `Logger` build time and changing `Logger::enabled` to accept `Level` instead of `&FilterCriteria`.
Expand Down Expand Up @@ -66,7 +66,7 @@ All significant changes to this project will be documented in this file.
* Make `Logger` a pointer-sized `Clone` and `Default` handle over a shared pipeline, add `const fn Logger::noop()`, `LoggerBuilder::new()` and `RecordBuilder::new()` (with `Default`), `const fn new()` on `PlainTextLayout`, `ThreadLocalDiagnostic`, `StderrErrorSink`, and `BlackHoleErrorSink`, and `new()` on `Stdout`, `Stderr`, and `Testing` in `logforth-core`, add `const fn new()` on `TaskLocalDiagnostic` in `logforth-diagnostic-task-local`, `FastraceDiagnostic` in `logforth-diagnostic-fastrace`, `FastraceEvent` in `logforth-append-fastrace`, and `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging`, add `new()` on `TextLayout`, `LogfmtLayout`, and `JsonLayout`, and implement `Clone`, `Default`, and `From<Logger>` for `LogBridge` in `logforth-bridge-log`.
* Add `Level::ALL` in `logforth-core` and `ValueOwned::{from_serde, try_from_serde}` (behind the `serde` feature) to convert `serde::Serialize` values into structured `ValueOwned` trees without panicking.
* Add `LogBridge::{max_level, logger, into_logger, try_install, install}` in `logforth-bridge-log`, and add `starter_log::{LogStarterExt, LogStarter::try_build}` (with `Debug` for `LogStarter`), `layout::{json, logfmt}` module re-exports, and the `serde` feature (`logforth-core/serde`) in `logforth`, updating `log::set_max_level` automatically from enabled logger levels on installation.
* Add `LoggerBuilder::error_sink`, `DispatchBuilder::error_sink`, and `starter_log::LogStarter::error_sink` to configure runtime error handling.
* Add `LoggerBuilder::error_sink` and `starter_log::LogStarter::error_sink` to configure runtime error handling.
* Implement `Append`, `ErrorSink`, `Filter`, and `Layout` in `logforth-core`, and `MakeBody` in `logforth-append-opentelemetry`, for `Arc<T>` and `&'static T` where `T: ?Sized`, and implement `Diagnostic` for `&T`, `Arc<T>`, `()`, `Option<T>`, slices, arrays, and `Vec` (including non-`'static` boxed trait objects).
* Add `FileBuilder::timezone` in `logforth-append-file` (and re-export `jiff`) to configure the timezone used for rotation boundaries and segment filenames, defaulting to the system timezone.
* Add `ThreadLocalDiagnostic::scope` and `ThreadLocalDiagnosticGuard` in `logforth-core` for `!Send` RAII scoped thread-local diagnostics that restore shadowed entries on drop.
Expand Down
4 changes: 2 additions & 2 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Logforth separates three concerns into distinct primitives:
- `Logger` is a lightweight `Clone` handle over a shared immutable pipeline, with no ambient global singleton in `logforth-core`. Applications expose process-wide channels through explicit statics or dependency injection, while libraries accepting an optional logger default to a zero-allocation `Logger::noop()`.
- All five extension points (`Filter`, `Diagnostic`, `Layout`, `Append`, and `ErrorSink`) are open object-safe traits paired with concrete types rather than closed enums or ad-hoc callbacks, forwarding shared references (`Arc<T>` and `&'static T`) so dispatches and loggers compose as a directed acyclic graph. `Diagnostic` omits a `'static` supertrait bound so decorators can chain stack-borrowed per-call context without allocation, enforcing `'static` only when registering long-lived diagnostics on a `Dispatch`.
- `Append` consumes structured records and diagnostics directly so protocol-native sinks encode typed fields without intermediate text serialization, whereas byte-stream sinks compose a `Layout` internally. `Layout` appends formatted bytes into reusable caller-supplied buffers without modifying prior contents or adding record framing (such as trailing newlines, which belong to the owning `Append`).
- Configuration placement follows pipeline role: `LoggerBuilder` sets the fallback `ErrorSink`, `DispatchBuilder` configures branch-wide filters, diagnostics, appenders, and optional `ErrorSink` overrides as a unit (skipping appender-less branches), and out-of-band executors manage their own worker `ErrorSink`.
- Configuration placement follows pipeline role: `LoggerBuilder` configures the pipeline `ErrorSink`, `DispatchBuilder` configures branch-wide filters, diagnostics, and appenders as a unit (skipping appender-less branches), and out-of-band executors manage their own worker `ErrorSink`.

## Filtering and Fast-Path Pruning

Expand All @@ -39,7 +39,7 @@ Logforth separates three concerns into distinct primitives:
## Error Handling and Operational Safety

- `Error` boxes its message and causal source chain so `Result<(), Error>` occupies a single pointer word on hot formatting, visiting, and appending paths.
- Logging pipelines must never panic on runtime operational failures such as out-of-range timestamps, broken pipes, closed descriptors, log rotation or retention errors, or fallible wire serialization. Leaf components return structured `Error`s (committing active record writes before surfacing post-write rollover or cleanup errors), execution roots and asynchronous workers isolate failures and panics via `ErrorSink`, and `ErrorSink` implementations silently absorb their own delivery failures without panicking or routing records back into their owning `Logger`.
- Logging pipelines must never panic on runtime operational failures such as out-of-range timestamps, broken pipes, closed descriptors, log rotation or retention errors, or fallible wire serialization. Leaf components return structured `Error`s (committing active record writes before surfacing post-write rollover or cleanup errors), synchronous execution roots route recoverable `Error`s to `ErrorSink` while asynchronous workers additionally isolate unwind panics via `ErrorSink`, and `ErrorSink` implementations silently absorb their own delivery failures without panicking or routing records back into their owning `Logger`.
- User `Display` and `Debug` formatting and value destruction execute outside appender I/O locks.
- Thread-local and task-local diagnostics access thread-local storage exclusively via fallible lookups (`LocalKey::try_with`) so logging during thread teardown degrades to an empty context instead of aborting.
- Because Rust does not run destructors on `static` items at process exit, buffered and asynchronous pipelines require an explicit `flush()` before shutdown.
Expand Down
5 changes: 2 additions & 3 deletions core/src/error/sink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ use crate::Error;
/// A terminal sink that processes internal runtime errors produced by the logging pipeline.
///
/// Logging operations are designed not to crash the host application at runtime. When an appender
/// fails to emit or flush records, execution roots such as [`Logger`](crate::Logger), an
/// overriding [`DispatchBuilder`](crate::DispatchBuilder), or asynchronous workers forward the
/// resulting [`Error`] to their configured [`ErrorSink`].
/// fails to emit or flush records, execution roots such as [`Logger`](crate::Logger) or asynchronous
/// workers forward the resulting [`Error`] to their configured [`ErrorSink`].
///
/// Because [`ErrorSink`] is the final stage of error handling, implementations operate on a
/// best-effort basis: they must silently absorb their own delivery failures, never panic, and
Expand Down
50 changes: 9 additions & 41 deletions core/src/logger/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ pub fn builder() -> LoggerBuilder {
LoggerBuilder::new()
}

/// A builder that assembles a [`Logger`] from ordered dispatch branches and a fallback
/// [`ErrorSink`].
/// A builder that assembles a [`Logger`] from ordered dispatch branches and an [`ErrorSink`].
///
/// # Examples
///
Expand All @@ -63,7 +62,7 @@ impl Default for LoggerBuilder {
}

impl LoggerBuilder {
/// Creates an empty [`LoggerBuilder`] with [`StderrErrorSink`] as the fallback error sink.
/// Creates an empty [`LoggerBuilder`] with [`StderrErrorSink`] as the logger's error sink.
pub fn new() -> Self {
Self {
dispatches: vec![],
Expand Down Expand Up @@ -94,10 +93,9 @@ impl LoggerBuilder {
self
}

/// Sets the fallback [`ErrorSink`] used when a dispatch fails to append or flush records.
/// Sets the logger's [`ErrorSink`] for append and flush failures.
///
/// Defaults to [`StderrErrorSink`]. Individual dispatches may override this via
/// [`DispatchBuilder::error_sink`].
/// Defaults to [`StderrErrorSink`].
///
/// # Examples
///
Expand Down Expand Up @@ -138,10 +136,10 @@ impl LoggerBuilder {

/// A builder for a single dispatch branch within a [`Logger`].
///
/// Configured filters, diagnostics, and any [`error_sink`](Self::error_sink) override apply to the
/// entire branch across all of its appenders regardless of method call order, while multiple
/// filters, diagnostics, or appenders preserve their respective registration order. A branch
/// configured with no appenders is skipped when registered on [`LoggerBuilder`].
/// Configured filters and diagnostics apply to all appenders in the branch regardless of method
/// call order, while multiple filters, diagnostics, or appenders preserve their respective
/// registration order. A branch configured with no appenders is skipped when registered on
/// [`LoggerBuilder`].
///
/// # Examples
///
Expand All @@ -162,7 +160,6 @@ pub struct DispatchBuilder {
filters: Vec<Box<dyn Filter>>,
diagnostics: Vec<Box<dyn Diagnostic>>,
appends: Vec<Box<dyn Append>>,
error_sink: Option<Box<dyn ErrorSink>>,
}

impl DispatchBuilder {
Expand All @@ -171,7 +168,6 @@ impl DispatchBuilder {
filters: vec![],
diagnostics: vec![],
appends: vec![],
error_sink: None,
}
}

Expand Down Expand Up @@ -219,29 +215,6 @@ impl DispatchBuilder {
self
}

/// Overrides the [`ErrorSink`] used when appenders in this dispatch fail.
///
/// Calling this method multiple times replaces any previously configured branch override. When
/// unset, errors from this dispatch fall back to [`LoggerBuilder::error_sink`].
///
/// # Examples
///
/// ```
/// use logforth_core::append;
/// use logforth_core::error::BlackHoleErrorSink;
///
/// let logger = logforth_core::builder()
/// .dispatch(|d| {
/// d.error_sink(BlackHoleErrorSink::default())
/// .append(append::Stdout::default())
/// })
/// .build();
/// ```
pub fn error_sink(mut self, error_sink: impl Into<Box<dyn ErrorSink>>) -> Self {
self.error_sink = Some(error_sink.into());
self
}

/// Appends an [`Append`] sink to receive records accepted by this dispatch.
///
/// # Examples
Expand All @@ -262,12 +235,7 @@ impl DispatchBuilder {
if self.appends.is_empty() {
None
} else {
Some(Dispatch::new(
self.filters,
self.diagnostics,
self.appends,
self.error_sink,
))
Some(Dispatch::new(self.filters, self.diagnostics, self.appends))
}
}
}
19 changes: 6 additions & 13 deletions core/src/logger/log_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,18 +105,17 @@ impl Logger {

/// Dispatches `record` across all configured branches in registration order.
///
/// If an appender returns an [`Error`], the error is forwarded to the branch's overriding
/// [`ErrorSink`] (or the logger's fallback [`ErrorSink`]) and remaining appenders still run.
/// If an appender returns an [`Error`], the error is forwarded to the logger's [`ErrorSink`]
/// and remaining appenders still run.
pub fn log(&self, record: &Record) {
let Some(state) = self.state.as_deref() else {
return;
};
if (state.level_mask & level_bit(record.level())) == 0 {
return;
}
let default_error_sink = &*state.error_sink;
for dispatch in &state.dispatches {
dispatch.log(record, default_error_sink);
dispatch.log(record, &*state.error_sink);
}
}

Expand All @@ -128,9 +127,8 @@ impl Logger {
let Some(state) = self.state.as_deref() else {
return;
};
let default_error_sink = &*state.error_sink;
for dispatch in &state.dispatches {
dispatch.flush(default_error_sink);
dispatch.flush(&*state.error_sink);
}
}
}
Expand All @@ -142,15 +140,13 @@ pub struct Dispatch {
filters: Vec<Box<dyn Filter>>,
diagnostics: Vec<Box<dyn Diagnostic>>,
appends: Vec<Box<dyn Append>>,
error_sink: Option<Box<dyn ErrorSink>>,
}

impl Dispatch {
pub fn new(
filters: Vec<Box<dyn Filter>>,
diagnostics: Vec<Box<dyn Diagnostic>>,
appends: Vec<Box<dyn Append>>,
error_sink: Option<Box<dyn ErrorSink>>,
) -> Self {
debug_assert!(
!appends.is_empty(),
Expand All @@ -169,11 +165,10 @@ impl Dispatch {
filters,
diagnostics,
appends,
error_sink,
}
}

fn log(&self, record: &Record, default_error_sink: &dyn ErrorSink) {
fn log(&self, record: &Record, error_sink: &dyn ErrorSink) {
if (self.level_mask & level_bit(record.level())) == 0 {
return;
}
Expand All @@ -187,7 +182,6 @@ impl Dispatch {
}
}

let error_sink = self.error_sink.as_deref().unwrap_or(default_error_sink);
for append in &self.appends {
if let Err(err) = append.append(record, diagnostics) {
let err = Error::new("failed to append record").with_source(err);
Expand All @@ -196,8 +190,7 @@ impl Dispatch {
}
}

fn flush(&self, default_error_sink: &dyn ErrorSink) {
let error_sink = self.error_sink.as_deref().unwrap_or(default_error_sink);
fn flush(&self, error_sink: &dyn ErrorSink) {
for append in &self.appends {
if let Err(err) = append.flush() {
let err = Error::new("failed to flush appender").with_source(err);
Expand Down
Loading
Loading