From cd8e42f40cda158630fb4892896b26a6735e55f0 Mon Sep 17 00:00:00 2001 From: tison Date: Tue, 1 Dec 2026 08:36:49 +0800 Subject: [PATCH 1/2] refactor(core): remove DispatchBuilder::error_sink and align docs Remove the unreleased `DispatchBuilder::error_sink` override and the per-dispatch `Option>` field on `Dispatch` so runtime error sinks are configured strictly at pipeline execution roots (`LoggerBuilder::error_sink`, `LogStarter::error_sink`, and `AsyncBuilder::error_sink`). Also fix two pre-release documentation inaccuracies: - `CHANGELOG.md`: record the prior `opentelemetry` and `opentelemetry_sdk` version as `0.32.0` instead of `0.31.0`, and drop unreleased `DispatchBuilder::error_sink` references. - `DESIGN.md`: align configuration placement with `LoggerBuilder` + out-of-band executors, and distinguish synchronous `Error` routing from asynchronous worker panic isolation. Signed-off-by: tison --- CHANGELOG.md | 6 +- DESIGN.md | 4 +- core/src/error/sink.rs | 5 +- core/src/logger/builder.rs | 50 +++-------------- core/src/logger/log_impl.rs | 21 +++---- tests-integration/tests/core_test/logger.rs | 62 +++++++++++---------- 6 files changed, 55 insertions(+), 93 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62bfd30..2634c1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` (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>`, `Error::with_source` accepts `impl Into>` instead of `impl Into` 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]` 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` 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` and return `Result<(), Error>` instead of `Result, 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`. @@ -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` 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` and `&'static T` where `T: ?Sized`, and implement `Diagnostic` for `&T`, `Arc`, `()`, `Option`, 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. diff --git a/DESIGN.md b/DESIGN.md index 15c003b..97bb11b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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` 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 @@ -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. diff --git a/core/src/error/sink.rs b/core/src/error/sink.rs index 74afd07..0770b3c 100644 --- a/core/src/error/sink.rs +++ b/core/src/error/sink.rs @@ -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 diff --git a/core/src/logger/builder.rs b/core/src/logger/builder.rs index 1cb04ed..5881621 100644 --- a/core/src/logger/builder.rs +++ b/core/src/logger/builder.rs @@ -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 /// @@ -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![], @@ -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 /// @@ -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 /// @@ -162,7 +160,6 @@ pub struct DispatchBuilder { filters: Vec>, diagnostics: Vec>, appends: Vec>, - error_sink: Option>, } impl DispatchBuilder { @@ -171,7 +168,6 @@ impl DispatchBuilder { filters: vec![], diagnostics: vec![], appends: vec![], - error_sink: None, } } @@ -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>) -> Self { - self.error_sink = Some(error_sink.into()); - self - } - /// Appends an [`Append`] sink to receive records accepted by this dispatch. /// /// # Examples @@ -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)) } } } diff --git a/core/src/logger/log_impl.rs b/core/src/logger/log_impl.rs index 6879b1b..47e44e6 100644 --- a/core/src/logger/log_impl.rs +++ b/core/src/logger/log_impl.rs @@ -105,8 +105,8 @@ 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; @@ -114,9 +114,8 @@ impl Logger { 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); } } @@ -128,21 +127,19 @@ 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); } } } /// A grouped set of filters, diagnostics, and appenders. #[derive(Debug)] -pub struct Dispatch { +pub(crate) struct Dispatch { level_mask: u32, filters: Vec>, diagnostics: Vec>, appends: Vec>, - error_sink: Option>, } impl Dispatch { @@ -150,7 +147,6 @@ impl Dispatch { filters: Vec>, diagnostics: Vec>, appends: Vec>, - error_sink: Option>, ) -> Self { debug_assert!( !appends.is_empty(), @@ -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; } @@ -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); @@ -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); diff --git a/tests-integration/tests/core_test/logger.rs b/tests-integration/tests/core_test/logger.rs index b4b815f..8e5b4a9 100644 --- a/tests-integration/tests/core_test/logger.rs +++ b/tests-integration/tests/core_test/logger.rs @@ -319,36 +319,27 @@ fn level_bitmask_prunes_disabled_levels_before_filter_evaluation_and_supports_pr } #[test] -fn error_routing_isolates_failing_appenders_and_applies_branch_overrides() { - let fallback_errors = RecordingErrorSink::default(); +fn error_routing_isolates_failing_appenders_across_branches() { let replaced_errors = RecordingErrorSink::default(); - let active_override_errors = RecordingErrorSink::default(); + let errors = RecordingErrorSink::default(); let healthy_sibling = RecordingAppender::default(); let healthy_trailing = RecordingAppender::default(); let logger = builder() - .error_sink(fallback_errors.clone()) + .error_sink(replaced_errors.clone()) .dispatch(|d| { d.append(FailingAppender::new("primary disk full")) .append(healthy_sibling.clone()) }) - .dispatch(|d| { - d.error_sink(BlackHoleErrorSink::default()) - .append(FailingAppender::new("silenced failure")) - }) - .dispatch(|d| { - d.error_sink(replaced_errors.clone()) - .error_sink(active_override_errors.clone()) - .append(FailingAppender::new("override network error")) - .append(healthy_trailing.clone()) - }) + .dispatch(|d| d.append(FailingAppender::new("network error"))) + .dispatch(|d| d.append(healthy_trailing.clone())) + .error_sink(errors.clone()) .build(); - logger.log( - &RecordBuilder::new() - .payload(format_args!("event-1")) - .build(), - ); + let record = RecordBuilder::new() + .payload(format_args!("event-1")) + .build(); + logger.log(&record); logger.flush(); assert_eq!(healthy_sibling.payloads(), ["event-1"]); @@ -358,19 +349,21 @@ fn error_routing_isolates_failing_appenders_and_applies_branch_overrides() { assert!(replaced_errors.errors().is_empty()); assert_eq!( - fallback_errors.errors(), + errors.errors(), [ "failed to append record: primary disk full", + "failed to append record: network error", "failed to flush appender: primary disk full", + "failed to flush appender: network error", ] ); - assert_eq!( - active_override_errors.errors(), - [ - "failed to append record: override network error", - "failed to flush appender: override network error", - ] - ); + + let silent_logger = builder() + .error_sink(BlackHoleErrorSink::new()) + .dispatch(|d| d.append(FailingAppender::new("silenced failure"))) + .build(); + silent_logger.log(&record); + silent_logger.flush(); } #[derive(Debug)] @@ -438,9 +431,9 @@ fn arc_and_static_forwarding_share_all_five_traits_across_dispatches() { // Exercise `new()` constructors alongside `&'static` forwarding of `const fn` ZST components. let _configured_std = LoggerBuilder::new() .error_sink(&STATIC_STDERR_SINK) + .error_sink(&STATIC_BLACK_HOLE_SINK) .dispatch(|d| { d.diagnostic(&STATIC_TLS_DIAG) - .error_sink(&STATIC_BLACK_HOLE_SINK) .append(Stdout::new().with_layout(&STATIC_PLAIN_LAYOUT)) .append(Stderr::new().with_layout(&STATIC_PLAIN_LAYOUT)) .append(Testing::new().with_layout(&STATIC_PLAIN_LAYOUT)) @@ -451,7 +444,17 @@ fn arc_and_static_forwarding_share_all_five_traits_across_dispatches() { let arc_layout: Arc = Arc::new(PrefixLayout("arc")); let arc_diag = Arc::new(StaticDiagnostic::new([("tenant", "acme")])); let arc_append = Arc::new(RecordingAppender::with_layout(arc_layout)); - let arc_error_sink: Arc = Arc::new(RecordingErrorSink::default()); + let errors = RecordingErrorSink::default(); + let arc_error_sink: Arc = Arc::new(errors.clone()); + let arc_logger = builder() + .error_sink(arc_error_sink) + .dispatch(|d| d.append(FailingAppender::new("arc sink error"))) + .build(); + arc_logger.flush(); + assert_eq!( + errors.errors(), + ["failed to flush appender: arc sink error"] + ); let logger = builder() .error_sink(&STATIC_ERROR_SINK) @@ -465,7 +468,6 @@ fn arc_and_static_forwarding_share_all_five_traits_across_dispatches() { let dyn_append: Arc = arc_append.clone(); d.filter(arc_filter.clone()) .diagnostic(dyn_diag) - .error_sink(arc_error_sink.clone()) .append(dyn_append) }) .dispatch(|d| { From 9d30a952d2b84bbadf8765599e28eaa48dcf6f00 Mon Sep 17 00:00:00 2001 From: tison Date: Tue, 1 Dec 2026 09:27:58 +0800 Subject: [PATCH 2/2] style(core): restore plain pub visibility on internal Dispatch struct `Dispatch` resides inside a private ancestor module tree (`mod logger` and `mod log_impl`) and is not re-exported, so plain `pub` matches the workspace visibility convention in `AGENTS.md`. Signed-off-by: tison --- core/src/logger/log_impl.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/logger/log_impl.rs b/core/src/logger/log_impl.rs index 47e44e6..482ad7f 100644 --- a/core/src/logger/log_impl.rs +++ b/core/src/logger/log_impl.rs @@ -135,7 +135,7 @@ impl Logger { /// A grouped set of filters, diagnostics, and appenders. #[derive(Debug)] -pub(crate) struct Dispatch { +pub struct Dispatch { level_mask: u32, filters: Vec>, diagnostics: Vec>,