From e6e30b88c957ab1890c6f3e3b2428a3a067ced9c Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 00:19:01 +0800 Subject: [PATCH 01/19] docs: add architectural design document for 1.0 Add `DESIGN.md` defining the architectural model, public contracts, and target `1.0` boundaries for `logforth-core` and its surrounding crates: - Pipeline topology separating source location, category (`target`), channel (`Logger`), and fan-out (`Dispatch`), plus `Arc` DAG sharing and `ErrorSink` fallback rules. - Core extension traits (`Filter`, `Diagnostic`, `Layout`, `Append`, `ErrorSink`), opaque `Diagnostics` view, and append-only `Layout` byte buffer contract. - Ternary `FilterResult` (`Accept`, `Reject`, `Neutral`) paired with backwards-inducted 24-level `LevelMask` fast-path pruning. - Structured key-value contracts (`ValueView::Str`, causal `ValueView::Error`, lossless ordered `ValueOwned`), operational safety invariants, `rustfmt`- and `Send`-safe native macros, bidirectional `log`/`tracing` interop, and external registry boundary. Signed-off-by: tison --- DESIGN.md | 119 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 DESIGN.md diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..fcf1cd3 --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,119 @@ +# Architecture and 1.0 Design + +This document defines the architectural model, public contracts, and target `1.0` design for `logforth-core` and its surrounding ecosystem crates. Runnable examples belong in [README.md](README.md) and crate-level API documentation. + +## Scope and Crate Versioning + +- Keep `logforth-core` at zero mandatory third-party dependencies so stabilizing `logforth-core 1.0` provides a permanent contract for `Logger`, `Record`, `kv`, and the five core extension traits without coupling SemVer stability to external SDKs. +- Evolve the `logforth` umbrella facade alongside peripheral appenders, layouts, filters, diagnostics, and ecosystem bridges on independent `0.x` tracks where dependencies such as `opentelemetry`, `jiff`, `fastrace`, `log`, and `tracing` change at their own pace. + +## Pipeline Topology and Assembly + +Logforth separates four concerns that legacy single-logger designs conflate into a single `target` string: + +| Dimension | Question Answered | Representation in Logforth | +| :------------------- | :-------------------------------------------------------- | :---------------------------------------------------------------------------------------------------- | +| Source location | Where in the source tree was the event emitted? | Compile-time `module_path`, `file`, `line`, and `column` on `Record` | +| Category (`target`) | Which logical module or subsystem emitted the event? | Hierarchical string on `Record` (defaulting to `module_path!()`) used for verbosity filtering | +| Channel (`Logger`) | Which reliability, schema, and lifecycle stream owns it? | Explicit `Logger` instances (for example, separating application diagnostics from `audit`/`metering`) | +| Fan-out (`Dispatch`) | Which output slices and destinations receive this stream? | Ordered `Dispatch` branches (`filters -> diagnostics -> appends`) inside a `Logger` | + +- `Logger` owns a `Vec` and a fallback `ErrorSink` without a global singleton in `logforth-core`. Callers share a `Logger` explicitly via `&Logger`, `Arc`, or `&'static Logger`, and libraries accepting an optional logger can default to a zero-allocation `const fn Logger::noop()`. +- All five component traits (`Append`, `Layout`, `Filter`, `Diagnostic`, and `ErrorSink`) implement forwarding for `Arc` and `&'static T`. Multiple dispatches or independent `Logger` instances can share stateful components such as `Arc` or `Arc` as a directed acyclic graph without introducing a mandatory `LoggerProvider` ceremony. +- Configuration follows component semantics rather than uniform inheritance: `DispatchBuilder::error_sink` optionally overrides `LoggerBuilder::error_sink` (falling back when unset), while `Filter` and `Diagnostic` stay at the `Dispatch` level in `1.0` (shared via `Arc` when needed) so a `RUST_LOG` filter on console output cannot accidentally silence a sibling audit or OTLP dispatch. Out-of-band executors such as `Async` spawn their worker before joining a `Logger` and therefore configure their own `ErrorSink` (sharable via `Arc`). + +## Core Extension Traits + +Every long-lived pipeline extension point is an object-safe trait (`fmt::Debug + Send + Sync + 'static`) paired with concrete struct implementations rather than closed enums or ad-hoc function pointers: + +```rust +pub trait Filter: fmt::Debug + Send + Sync + 'static { + fn level_bounds(&self) -> FilterLevelBounds { FilterLevelBounds::ALL } + fn enabled(&self, criteria: &FilterCriteria, diags: Diagnostics) -> FilterResult; + fn matches(&self, record: &Record, diags: Diagnostics) -> FilterResult { ... } +} + +pub trait Diagnostic: fmt::Debug + Send + Sync + 'static { + fn visit(&self, visitor: &mut dyn kv::Visitor) -> Result<(), Error>; +} + +pub trait Layout: fmt::Debug + Send + Sync + 'static { + fn format(&self, record: &Record, diags: Diagnostics, buf: &mut Vec) -> Result<(), Error>; +} + +pub trait Append: fmt::Debug + Send + Sync + 'static { + fn append(&self, record: &Record, diags: Diagnostics) -> Result<(), Error>; + fn flush(&self) -> Result<(), Error>; +} + +pub trait ErrorSink: fmt::Debug + Send + Sync + 'static { + fn sink(&self, err: &Error); +} +``` + +- `Diagnostics<'a>` is a `Copy` opaque view abstracting over `&'a [Box]`, `&'a [&'a dyn Diagnostic]`, a single stack `&'a dyn Diagnostic`, or chained scopes. Replacing `&[Box]` decouples public traits from `Dispatch`'s storage and eliminates per-record heap boxing in `Async` workers. +- `Layout::format` appends formatted bytes into a caller-supplied `&mut Vec` rather than returning a fresh `Vec` or writing piecemeal into `&mut dyn io::Write`: + 1. Implementations must only append to `buf` (never clearing or reading prior bytes), and callers must truncate `buf` back to its starting length on `Err`. + 2. Record framing (such as trailing `\n`) belongs to the owning `Append`, not `Layout`. + 3. Synchronous appenders may pool thread-local `Vec` buffers outside I/O locks using `try_borrow_mut` (falling back to a fresh `Vec` on reentrant logging inside user `Display::fmt`). + +## Filtering and Fast-Path Pruning + +- `Level` defines 24 exhaustive severity variants (`#[repr(u8)]` `1..=24`, `Trace` through `Fatal4`) mapped 1-to-1 to OpenTelemetry `SeverityNumber` while leaving 232 niche values for compact enum layout. +- `FilterResult` retains Logback and `iptables` ternary semantics: + - `Reject` drops the record immediately from the current `Dispatch`. + - `Accept` short-circuits remaining filters in the current `Dispatch` and accepts the record immediately, enabling diagnostic-driven dynamic overrides (such as promoting a specific request or trace in `TaskLocalDiagnostic` to `Debug` ahead of a baseline `RustLogFilter`). + - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. +- Two-phase invariant: `Filter::enabled` is a conservative pre-check before `Record` construction. If `enabled` returns `Reject`, `matches` must also reject; if `matches` can short-circuit with `Accept` based on payload or key-values, `enabled` must conservatively return `Accept` when followed by a stricter filter. +- `LevelMask(u32)` represents any subset of the 24 levels (including non-monotonic `LevelFilter` predicates such as `Equal` or `MoreVerbose`) in a single register. Each `Filter` reports static `(may_accept, may_neutral)` masks (`LevelFilter` and `RustLogFilter` report `may_accept = NONE`), and `DispatchBuilder::build` computes the dispatch's `LevelMask` via backwards induction `mask = may_accept | (may_neutral & next)`, folding pure `LevelFilter` items so common level-only dispatches allocate zero `Box` objects. +- `Logger::enabled` tests each dispatch's `LevelMask` with a single bitwise AND before invoking virtual filters. Attaching a leading diagnostic `Accept` override intentionally widens that dispatch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` in `1.0`. + +## Structured Key-Values and Diagnostics + +- Borrowed-to-owned duality: synchronous paths carry stack-borrowed `Record<'a>`, `Key<'a>`, and `Value<'a>` (backed by `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals), whereas `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that async workers re-project via `RecordOwned::with`. +- `ValueView<'a>` (`#[non_exhaustive]`) refines three contracts for `1.0`: + 1. Unify `BorrowedStr` and `StaticStr` into a single `ValueView::Str(StrValue<'a>)` variant exposing `as_str(&self) -> &'a str` and `as_static_str(&self) -> Option<&'static str>`, preventing `#[non_exhaustive]` wildcard arms in third-party layouts from silently mishandling static strings. + 2. Add first-class `Value::error(&'a (dyn StdError + 'static))` and `ValueView::Error(ErrorValue<'a>)` (exposing `as_std()` when borrowed and iterating/formatting the full `.source()` chain, promoted to `Box<[Cow<'static, str>]>` in `ValueOwned`) so structured JSON, GCP, OpenTelemetry, and bridge outputs preserve causal error chains. + 3. Expose `KeyView::as_static_str`, `ValueView::to_bytes`, and `ValueView::is_none`, plus `From>` and `From<&'a Cow<'_, str>>` conversions. +- Lossless owned storage: `ValueOwned` uses `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` (removing `HashMap` constructors) so synchronous and asynchronous paths preserve identical key ordering and duplicate-key semantics. +- Built-in diagnostics (`StaticDiagnostic`, `ThreadLocalDiagnostic` with RAII scope guards, and `TaskLocalDiagnostic`) uniformly store `(KeyOwned, ValueOwned)`. Diagnostic visitors may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. + +## Error Handling and Operational Safety + +- `Error` boxes its payload (`Cow<'static, str>` message plus optional `Box` source) so `Result<(), Error>` occupies a single machine word (`8` bytes on 64-bit targets) on hot `Visitor`, `Layout`, and `Append` return paths. +- Non-crashing runtime rule: logging pipelines must never `panic!` or `.unwrap()` on fallible user `Display`/`Debug` implementations, out-of-range timestamps, broken pipes (`EPIPE`), closed descriptors, or log rotation errors. Leaf components return `Err(Error)` with operation-specific messages; `RollingFileWriter` writes the current record to the active file before returning any rollover or cleanup error. +- Threading, TLS, and unwind safety: + - User `Display`/`Debug` formatting always executes on the caller thread outside appender I/O mutexes (`Record::to_owned` snapshots payloads on the caller thread before enqueuing to `Async`). + - `ThreadLocalDiagnostic` and `TaskLocalDiagnostic` access thread-local storage exclusively via `LocalKey::try_with` so logging from TLS destructors during thread teardown degrades gracefully to empty context instead of aborting. + - `Async` workers guard per-record dispatch with `catch_unwind` (reporting panics via `ErrorSink`) and never `.expect()` when joining worker threads in `Drop`. Because Rust does not drop `static` items at process exit, global bridges require explicit `flush()` before shutdown. + +## Native Logging Macros + +```rust +logforth::info!(logger, "listening on {}", addr); +logforth::info!(logger, ["port" = port, tls = true], "server started"); +logforth::info!(logger, ["jobs.completed" = count]); +logforth::info!(logger, target = "statement", ["rows" = n], "query finished"); +``` + +- Tooling compatibility: structured fields use bracketed assignment expressions (`["k" = v, flag = v2]`) before the format string, and optional category overrides use `target = "..."` rather than `target: "..."`. Every argument is a valid Rust `ast::Expr`, allowing `rustfmt` to format the entire macro invocation cleanly without colliding with `format_args!` named parameters. +- Evaluation and `async` `Send` safety: `$logger` and `$level` evaluate exactly once. When `logger.enabled(&criteria)` succeeds, value expressions evaluate at most once and bind shared references (`let (v0, ...) = (&$v0, ...);`) before constructing `!Send` `Value<'_>` or `fmt::Arguments<'_>` temporaries, ensuring `Future`s that `.await` inside log arguments remain `Send`. +- Zero-copy keys and compact codegen: string literal keys (`"jobs.completed"`) and identifier shorthands (`tls`) expand to `Key::new` (`'static` provenance), and record construction delegates to a non-generic `__private_log` function backed by a `static` callsite location descriptor. `Level::Fatal` records severity metadata only and neither flushes nor terminates the process. + +## Ecosystem Interop and Bridges + +Logforth provides bidirectional adapters modeled after SLF4J so applications and libraries can adopt native `Logger` pipelines incrementally alongside `log` and `tracing`: + +| Direction | Crate | Role | +| :--------------------------------------- | :------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------- | +| Inbound (`log` -> `logforth`) | `logforth-bridge-log` | Implements `log::Log` (`LogBridge`), preserving `log::kv` types and setting `log::set_max_level` from `Logger`'s `LevelMask` across the 5 levels | +| Inbound (`tracing` -> `logforth`) | `logforth-bridge-tracing` | Implements `tracing_subscriber::Layer`, translating `tracing::Event` fields (including `record_error`) and flattening `event_scope()` span kvs | +| Outbound (`logforth` -> `log`/`tracing`) | `logforth-append-log` | Implements `Append` by forwarding `Record` and `Diagnostics` to `log::logger()`, supporting both `log` hosts and `tracing-log` hosts | + +- Libraries adopting `logforth` natively can accept an injected `Logger` whose default routes to `logforth-append-log` (or `Logger::noop()`), remaining observable inside host applications that have not yet migrated to `logforth`. +- Loop prevention: if `LogBridge` is installed as the global `log` logger while a dispatch also attaches `logforth-append-log`, a panic-safe thread-local guard set by `logforth-append-log` and checked at `LogBridge` entry breaks the cycle, drops the reentrant record, and reports the misconfiguration once via `ErrorSink`. + +## Registry Boundary + +- `logforth-core` deliberately omits a global named logger registry. Global registries couple core APIs to initialization-order races, ambiguous shutdown/flush ownership, and configuration-driven type registration (`log4rs`-style dependency fan-in), while general-purpose crates on crates.io cannot assume a `logforth` registry exists. +- Applications requiring configuration-driven named routing, dynamic per-component reconfiguration, or administrative endpoints should layer an optional external `logforth-registry` crate purely atop `logforth-core`'s public primitives (`Arc`, `Arc` component sharing, and external atomic pointer swaps such as `ArcSwap`). Any registry requirement that cannot be expressed through public `logforth-core` traits indicates a missing composable primitive rather than a reason to embed a registry in `core`. From cfbdef2848ccf577b83caeeef4c2cd9c39f284eb Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 01:12:04 +0800 Subject: [PATCH 02/19] docs: refine DESIGN.md as a first-principles specification Rewrite `DESIGN.md` as a self-contained target specification rather than a diff against existing `0.x` internals: - Drop special `target` fields and `FilterCriteria` in favor of `Record::module_path`, `Logger::level_enabled`, and single-pass `Filter::check(&Record, Diagnostics)` paired with `Filter::bounds`. - Add the `Diagnostics<'a>` view sketch, retain `#[non_exhaustive]` and existing string variants on `ValueView`, separate normative contracts from examples, and remove parenthetical clutter and chat-specific comparisons. Signed-off-by: tison --- DESIGN.md | 113 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 64 insertions(+), 49 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index fcf1cd3..2e2cf6d 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -4,23 +4,24 @@ This document defines the architectural model, public contracts, and target `1.0 ## Scope and Crate Versioning -- Keep `logforth-core` at zero mandatory third-party dependencies so stabilizing `logforth-core 1.0` provides a permanent contract for `Logger`, `Record`, `kv`, and the five core extension traits without coupling SemVer stability to external SDKs. -- Evolve the `logforth` umbrella facade alongside peripheral appenders, layouts, filters, diagnostics, and ecosystem bridges on independent `0.x` tracks where dependencies such as `opentelemetry`, `jiff`, `fastrace`, `log`, and `tracing` change at their own pace. +- `logforth-core` carries zero mandatory third-party dependencies. Stabilizing `logforth-core 1.0` establishes a permanent contract for `Logger`, `Record`, `kv`, and the five core extension traits without coupling SemVer stability to external SDKs. +- The `logforth` umbrella facade and peripheral appenders, layouts, filters, diagnostics, and ecosystem bridges evolve on independent `0.x` tracks so external dependencies such as `opentelemetry`, `jiff`, `fastrace`, `log`, and `tracing` can upgrade at their own pace. ## Pipeline Topology and Assembly -Logforth separates four concerns that legacy single-logger designs conflate into a single `target` string: +Logforth separates three concerns into distinct primitives: -| Dimension | Question Answered | Representation in Logforth | -| :------------------- | :-------------------------------------------------------- | :---------------------------------------------------------------------------------------------------- | -| Source location | Where in the source tree was the event emitted? | Compile-time `module_path`, `file`, `line`, and `column` on `Record` | -| Category (`target`) | Which logical module or subsystem emitted the event? | Hierarchical string on `Record` (defaulting to `module_path!()`) used for verbosity filtering | -| Channel (`Logger`) | Which reliability, schema, and lifecycle stream owns it? | Explicit `Logger` instances (for example, separating application diagnostics from `audit`/`metering`) | -| Fan-out (`Dispatch`) | Which output slices and destinations receive this stream? | Ordered `Dispatch` branches (`filters -> diagnostics -> appends`) inside a `Logger` | +| Dimension | Question Answered | Representation in Logforth | +| :------------------- | :-------------------------------------------------------- | :------------------------------------------------------------ | +| Source location | Where in the source tree was the event emitted? | Compile-time `module_path`, `file`, `line`, and `column` | +| Channel (`Logger`) | Which reliability, schema, and lifecycle stream owns it? | Explicit `Logger` instances | +| Fan-out (`Dispatch`) | Which output slices and destinations receive this stream? | Ordered `Dispatch` branches inside a `Logger` | - `Logger` owns a `Vec` and a fallback `ErrorSink` without a global singleton in `logforth-core`. Callers share a `Logger` explicitly via `&Logger`, `Arc`, or `&'static Logger`, and libraries accepting an optional logger can default to a zero-allocation `const fn Logger::noop()`. -- All five component traits (`Append`, `Layout`, `Filter`, `Diagnostic`, and `ErrorSink`) implement forwarding for `Arc` and `&'static T`. Multiple dispatches or independent `Logger` instances can share stateful components such as `Arc` or `Arc` as a directed acyclic graph without introducing a mandatory `LoggerProvider` ceremony. -- Configuration follows component semantics rather than uniform inheritance: `DispatchBuilder::error_sink` optionally overrides `LoggerBuilder::error_sink` (falling back when unset), while `Filter` and `Diagnostic` stay at the `Dispatch` level in `1.0` (shared via `Arc` when needed) so a `RUST_LOG` filter on console output cannot accidentally silence a sibling audit or OTLP dispatch. Out-of-band executors such as `Async` spawn their worker before joining a `Logger` and therefore configure their own `ErrorSink` (sharable via `Arc`). +- All five component traits (`Append`, `Layout`, `Filter`, `Diagnostic`, and `ErrorSink`) implement forwarding for `Arc` and `&'static T`. Multiple dispatches or independent `Logger` instances can share stateful components as a directed acyclic graph without a separate provider wrapper. +- Configuration placement follows each component's role in the pipeline. `LoggerBuilder::error_sink` sets the logger-wide failure fallback, and `DispatchBuilder::error_sink` optionally overrides it for a specific branch. Out-of-band executors such as `Async` manage an independent worker lifecycle and configure their own `ErrorSink`. `Filter` and `Diagnostic` are configured on `DispatchBuilder` because branches within a `Logger` exist to select distinct event subsets and context; branches that share a filter or diagnostic share it explicitly via `Arc`. + +For example, an application can isolate `audit` events on a dedicated `Logger` while its main diagnostic `Logger` fans out `Warn` records to standard error and `Debug` records to a shared `Arc`. ## Core Extension Traits @@ -28,9 +29,8 @@ Every long-lived pipeline extension point is an object-safe trait (`fmt::Debug + ```rust pub trait Filter: fmt::Debug + Send + Sync + 'static { - fn level_bounds(&self) -> FilterLevelBounds { FilterLevelBounds::ALL } - fn enabled(&self, criteria: &FilterCriteria, diags: Diagnostics) -> FilterResult; - fn matches(&self, record: &Record, diags: Diagnostics) -> FilterResult { ... } + fn bounds(&self) -> FilterBounds { FilterBounds::ALL } + fn check(&self, record: &Record, diags: Diagnostics) -> FilterResult; } pub trait Diagnostic: fmt::Debug + Send + Sync + 'static { @@ -51,41 +51,56 @@ pub trait ErrorSink: fmt::Debug + Send + Sync + 'static { } ``` -- `Diagnostics<'a>` is a `Copy` opaque view abstracting over `&'a [Box]`, `&'a [&'a dyn Diagnostic]`, a single stack `&'a dyn Diagnostic`, or chained scopes. Replacing `&[Box]` decouples public traits from `Dispatch`'s storage and eliminates per-record heap boxing in `Async` workers. -- `Layout::format` appends formatted bytes into a caller-supplied `&mut Vec` rather than returning a fresh `Vec` or writing piecemeal into `&mut dyn io::Write`: - 1. Implementations must only append to `buf` (never clearing or reading prior bytes), and callers must truncate `buf` back to its starting length on `Err`. - 2. Record framing (such as trailing `\n`) belongs to the owning `Append`, not `Layout`. - 3. Synchronous appenders may pool thread-local `Vec` buffers outside I/O locks using `try_borrow_mut` (falling back to a fresh `Vec` on reentrant logging inside user `Display::fmt`). +`Diagnostics<'a>` is a `Copy` view passed to filters, layouts, and appenders without exposing internal container types: + +```rust +#[derive(Clone, Copy)] +pub struct Diagnostics<'a>(DiagnosticsInner<'a>); + +#[derive(Clone, Copy)] +enum DiagnosticsInner<'a> { + Empty, + // Borrows a Dispatch's owned diagnostic list without copying or re-boxing. + Boxed(&'a [Box]), + // Borrows a stack-resident diagnostic, such as materialized context in an async worker. + Single(&'a dyn Diagnostic), + // Borrows a slice of trait-object references for ad-hoc composition and testing. + Slice(&'a [&'a dyn Diagnostic]), +} +``` + +- `Append` consumes structured `&Record` and `Diagnostics` directly so protocol-native sinks can encode typed fields without intermediate text serialization, whereas byte-stream sinks compose a `Layout` internally. +- `Layout::format` appends formatted bytes into a caller-supplied `&mut Vec`: + 1. Implementations must only append to `buf` without clearing or reading prior bytes, and callers must truncate `buf` back to its starting length on `Err`. + 2. Record framing such as a trailing newline belongs to the owning `Append`, not `Layout`. + 3. Synchronous appenders may pool thread-local `Vec` buffers outside I/O locks via `try_borrow_mut`, falling back to a fresh `Vec` if user `Display::fmt` logs reentrantly. ## Filtering and Fast-Path Pruning -- `Level` defines 24 exhaustive severity variants (`#[repr(u8)]` `1..=24`, `Trace` through `Fatal4`) mapped 1-to-1 to OpenTelemetry `SeverityNumber` while leaving 232 niche values for compact enum layout. -- `FilterResult` retains Logback and `iptables` ternary semantics: +- `Level` defines 24 exhaustive severity variants with `#[repr(u8)]` discriminants `1..=24` from `Trace` through `Fatal4`, aligned 1-to-1 with OpenTelemetry `SeverityNumber` while leaving 232 niche values for compact enum layout. +- `FilterResult` models an ordered decision chain with three outcomes: - `Reject` drops the record immediately from the current `Dispatch`. - - `Accept` short-circuits remaining filters in the current `Dispatch` and accepts the record immediately, enabling diagnostic-driven dynamic overrides (such as promoting a specific request or trace in `TaskLocalDiagnostic` to `Debug` ahead of a baseline `RustLogFilter`). + - `Accept` short-circuits remaining filters in the current `Dispatch` and accepts the record immediately, supporting context-driven dynamic promotion ahead of baseline level thresholds. - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. -- Two-phase invariant: `Filter::enabled` is a conservative pre-check before `Record` construction. If `enabled` returns `Reject`, `matches` must also reject; if `matches` can short-circuit with `Accept` based on payload or key-values, `enabled` must conservatively return `Accept` when followed by a stricter filter. -- `LevelMask(u32)` represents any subset of the 24 levels (including non-monotonic `LevelFilter` predicates such as `Equal` or `MoreVerbose`) in a single register. Each `Filter` reports static `(may_accept, may_neutral)` masks (`LevelFilter` and `RustLogFilter` report `may_accept = NONE`), and `DispatchBuilder::build` computes the dispatch's `LevelMask` via backwards induction `mask = may_accept | (may_neutral & next)`, folding pure `LevelFilter` items so common level-only dispatches allocate zero `Box` objects. -- `Logger::enabled` tests each dispatch's `LevelMask` with a single bitwise AND before invoking virtual filters. Attaching a leading diagnostic `Accept` override intentionally widens that dispatch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` in `1.0`. +- `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`. `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)` and folds pure `LevelFilter` items directly into the mask without retaining `Box` allocations. +- `Logger::level_enabled(level)` tests each dispatch's `LevelMask` with a bitwise AND before a callsite constructs a `Record`, and `Logger::enabled(&record)` evaluates dispatch masks and filters without invoking appenders. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` in `1.0`. +- Module-level switching operates at two granularities without scanning `Record::key_values()`: subsystems that hold dedicated `Logger` instances achieve `O(1)` callsite pruning via `Logger::level_enabled`, while a shared `Logger` using `RustLogFilter` reads `Record::module_path()` in `O(1)` after passing the level mask. ## Structured Key-Values and Diagnostics -- Borrowed-to-owned duality: synchronous paths carry stack-borrowed `Record<'a>`, `Key<'a>`, and `Value<'a>` (backed by `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals), whereas `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that async workers re-project via `RecordOwned::with`. -- `ValueView<'a>` (`#[non_exhaustive]`) refines three contracts for `1.0`: - 1. Unify `BorrowedStr` and `StaticStr` into a single `ValueView::Str(StrValue<'a>)` variant exposing `as_str(&self) -> &'a str` and `as_static_str(&self) -> Option<&'static str>`, preventing `#[non_exhaustive]` wildcard arms in third-party layouts from silently mishandling static strings. - 2. Add first-class `Value::error(&'a (dyn StdError + 'static))` and `ValueView::Error(ErrorValue<'a>)` (exposing `as_std()` when borrowed and iterating/formatting the full `.source()` chain, promoted to `Box<[Cow<'static, str>]>` in `ValueOwned`) so structured JSON, GCP, OpenTelemetry, and bridge outputs preserve causal error chains. - 3. Expose `KeyView::as_static_str`, `ValueView::to_bytes`, and `ValueView::is_none`, plus `From>` and `From<&'a Cow<'_, str>>` conversions. -- Lossless owned storage: `ValueOwned` uses `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` (removing `HashMap` constructors) so synchronous and asynchronous paths preserve identical key ordering and duplicate-key semantics. -- Built-in diagnostics (`StaticDiagnostic`, `ThreadLocalDiagnostic` with RAII scope guards, and `TaskLocalDiagnostic`) uniformly store `(KeyOwned, ValueOwned)`. Diagnostic visitors may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. +- `Record<'a>` carries `time`, `level`, `module_path`, `file`, `line`, `column`, `payload`, and a zero-allocation `KeyValues<'a>` slice without a separate `target` field. +- Synchronous paths borrow `Record<'a>`, `Key<'a>`, and `Value<'a>` on the caller stack, using `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals. Across asynchronous boundaries, `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that workers re-project via `RecordOwned::with`. +- `ValueView<'a>` is marked `#[non_exhaustive]` and implements `fmt::Display` so unhandled variants always degrade cleanly to strings. `Value::error(&'a (dyn StdError + 'static))` and `ValueView::Error(ErrorValue<'a>)` preserve full `.source()` causal chains: `Display` renders the complete chain for text consumers, borrowed views expose the underlying `dyn StdError`, and `ValueOwned` snapshots the chain as `Box<[Cow<'static, str>]>`. `KeyView` and `ValueView` also expose `as_static_str`, `to_bytes`, and `is_none` accessors alongside `From>` and `From<&'a Cow<'_, str>>` conversions. +- `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics. +- `StaticDiagnostic`, `ThreadLocalDiagnostic` with RAII scope guards, and `TaskLocalDiagnostic` store `(KeyOwned, ValueOwned)`. `Diagnostic::visit` may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. ## Error Handling and Operational Safety -- `Error` boxes its payload (`Cow<'static, str>` message plus optional `Box` source) so `Result<(), Error>` occupies a single machine word (`8` bytes on 64-bit targets) on hot `Visitor`, `Layout`, and `Append` return paths. -- Non-crashing runtime rule: logging pipelines must never `panic!` or `.unwrap()` on fallible user `Display`/`Debug` implementations, out-of-range timestamps, broken pipes (`EPIPE`), closed descriptors, or log rotation errors. Leaf components return `Err(Error)` with operation-specific messages; `RollingFileWriter` writes the current record to the active file before returning any rollover or cleanup error. -- Threading, TLS, and unwind safety: - - User `Display`/`Debug` formatting always executes on the caller thread outside appender I/O mutexes (`Record::to_owned` snapshots payloads on the caller thread before enqueuing to `Async`). - - `ThreadLocalDiagnostic` and `TaskLocalDiagnostic` access thread-local storage exclusively via `LocalKey::try_with` so logging from TLS destructors during thread teardown degrades gracefully to empty context instead of aborting. - - `Async` workers guard per-record dispatch with `catch_unwind` (reporting panics via `ErrorSink`) and never `.expect()` when joining worker threads in `Drop`. Because Rust does not drop `static` items at process exit, global bridges require explicit `flush()` before shutdown. +- `Error` boxes its `Cow<'static, str>` message and optional `Box` cause so `Result<(), Error>` occupies a single word on hot `Visitor`, `Layout`, and `Append` return paths. +- Logging pipelines must never `panic!` or `.unwrap()` on fallible user `Display` or `Debug` implementations, out-of-range timestamps, broken pipes, closed descriptors, or log rotation failures. Leaf components return `Err(Error)` with operation-specific messages, and `RollingFileWriter` writes the current record to the active file before surfacing any rollover or cleanup error. +- User `Display` and `Debug` formatting always runs on the caller thread outside appender I/O mutexes. +- `ThreadLocalDiagnostic` and `TaskLocalDiagnostic` access thread-local storage exclusively via `LocalKey::try_with` so logging from TLS destructors during thread teardown degrades to empty context instead of aborting. +- `Async` workers isolate per-record dispatch with `catch_unwind`, report panics via `ErrorSink`, and avoid `.expect()` when joining worker threads in `Drop`. Because Rust does not run destructors on `static` items at process exit, global bridges require an explicit `flush()` before shutdown. ## Native Logging Macros @@ -93,27 +108,27 @@ pub trait ErrorSink: fmt::Debug + Send + Sync + 'static { logforth::info!(logger, "listening on {}", addr); logforth::info!(logger, ["port" = port, tls = true], "server started"); logforth::info!(logger, ["jobs.completed" = count]); -logforth::info!(logger, target = "statement", ["rows" = n], "query finished"); ``` -- Tooling compatibility: structured fields use bracketed assignment expressions (`["k" = v, flag = v2]`) before the format string, and optional category overrides use `target = "..."` rather than `target: "..."`. Every argument is a valid Rust `ast::Expr`, allowing `rustfmt` to format the entire macro invocation cleanly without colliding with `format_args!` named parameters. -- Evaluation and `async` `Send` safety: `$logger` and `$level` evaluate exactly once. When `logger.enabled(&criteria)` succeeds, value expressions evaluate at most once and bind shared references (`let (v0, ...) = (&$v0, ...);`) before constructing `!Send` `Value<'_>` or `fmt::Arguments<'_>` temporaries, ensuring `Future`s that `.await` inside log arguments remain `Send`. -- Zero-copy keys and compact codegen: string literal keys (`"jobs.completed"`) and identifier shorthands (`tls`) expand to `Key::new` (`'static` provenance), and record construction delegates to a non-generic `__private_log` function backed by a `static` callsite location descriptor. `Level::Fatal` records severity metadata only and neither flushes nor terminates the process. +- Structured fields precede the format string using bracketed assignment expressions. Every macro argument is a valid Rust `ast::Expr` so `rustfmt` formats the entire invocation without colliding with `format_args!` named parameters. +- `$logger` and `$level` evaluate once. When `logger.level_enabled(level)` succeeds, value expressions evaluate at most once and bind shared references before constructing `!Send` `Value<'_>` or `fmt::Arguments<'_>` temporaries, keeping enclosing `async` futures `Send` across `.await` points inside log arguments. +- String literal keys and identifier shorthands expand to `Key::new` with `'static` provenance, and record construction delegates to a non-generic `__private_log` helper backed by a `static` callsite location descriptor. `Level::Fatal` records severity metadata only and neither flushes nor terminates the process. ## Ecosystem Interop and Bridges -Logforth provides bidirectional adapters modeled after SLF4J so applications and libraries can adopt native `Logger` pipelines incrementally alongside `log` and `tracing`: +Logforth provides bidirectional adapters for `log` and `tracing` so applications and libraries can adopt native `Logger` pipelines incrementally: | Direction | Crate | Role | | :--------------------------------------- | :------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------- | -| Inbound (`log` -> `logforth`) | `logforth-bridge-log` | Implements `log::Log` (`LogBridge`), preserving `log::kv` types and setting `log::set_max_level` from `Logger`'s `LevelMask` across the 5 levels | -| Inbound (`tracing` -> `logforth`) | `logforth-bridge-tracing` | Implements `tracing_subscriber::Layer`, translating `tracing::Event` fields (including `record_error`) and flattening `event_scope()` span kvs | +| Inbound (`log` -> `logforth`) | `logforth-bridge-log` | Implements `log::Log`, mapping `log::Record::target()` to `Record::module_path` and setting `log::set_max_level` from `Logger`'s `LevelMask` | +| Inbound (`tracing` -> `logforth`) | `logforth-bridge-tracing` | Implements `tracing_subscriber::Layer`, translating `tracing::Event` fields and flattening active `event_scope()` span attributes into `Record` | | Outbound (`logforth` -> `log`/`tracing`) | `logforth-append-log` | Implements `Append` by forwarding `Record` and `Diagnostics` to `log::logger()`, supporting both `log` hosts and `tracing-log` hosts | -- Libraries adopting `logforth` natively can accept an injected `Logger` whose default routes to `logforth-append-log` (or `Logger::noop()`), remaining observable inside host applications that have not yet migrated to `logforth`. -- Loop prevention: if `LogBridge` is installed as the global `log` logger while a dispatch also attaches `logforth-append-log`, a panic-safe thread-local guard set by `logforth-append-log` and checked at `LogBridge` entry breaks the cycle, drops the reentrant record, and reports the misconfiguration once via `ErrorSink`. +- `LogBridge::enabled` checks `Logger::level_enabled` first and falls back to `Logger::enabled` with a stack-allocated `Record` carrying the metadata module path when callers invoke `log::log_enabled!`. +- Libraries adopting `logforth` natively can accept an injected `Logger` whose default routes to `logforth-append-log` or `Logger::noop()`, remaining observable inside host applications that use another subscriber. +- If `LogBridge` is installed as the global `log` logger while a dispatch also attaches `logforth-append-log`, a panic-safe thread-local guard set by `logforth-append-log` and checked at `LogBridge` entry breaks the cycle, drops the reentrant record, and reports the misconfiguration once via `ErrorSink`. ## Registry Boundary -- `logforth-core` deliberately omits a global named logger registry. Global registries couple core APIs to initialization-order races, ambiguous shutdown/flush ownership, and configuration-driven type registration (`log4rs`-style dependency fan-in), while general-purpose crates on crates.io cannot assume a `logforth` registry exists. -- Applications requiring configuration-driven named routing, dynamic per-component reconfiguration, or administrative endpoints should layer an optional external `logforth-registry` crate purely atop `logforth-core`'s public primitives (`Arc`, `Arc` component sharing, and external atomic pointer swaps such as `ArcSwap`). Any registry requirement that cannot be expressed through public `logforth-core` traits indicates a missing composable primitive rather than a reason to embed a registry in `core`. +- `logforth-core` omits a global named logger registry to avoid initialization-order races, ambiguous shutdown and flush ownership, and configuration-driven dependency fan-in, as crates on crates.io cannot assume a `logforth` registry exists. +- Applications requiring configuration-driven named routing, acquisition-time `O(1)` module level resolution, or runtime reconfiguration layer an optional external `logforth-registry` crate atop `logforth-core`'s public primitives (`Arc`, `Arc` component sharing, and atomic pointer swaps). Any registry requirement that cannot be expressed through public `logforth-core` traits indicates a missing composable primitive rather than a reason to embed a registry in `core`. From a3945f5725018946a1117f2cad53d6f49e96be62 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 01:14:42 +0800 Subject: [PATCH 03/19] docs: remove remaining diff-style phrasing in DESIGN.md State `Record` fields, dynamic filter mask semantics, and `Value`/`ValueView` conversions as complete standalone contracts rather than listing incremental additions or exclusions relative to pre-1.0 code. Signed-off-by: tison --- DESIGN.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 2e2cf6d..dc816ed 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -83,14 +83,14 @@ enum DiagnosticsInner<'a> { - `Accept` short-circuits remaining filters in the current `Dispatch` and accepts the record immediately, supporting context-driven dynamic promotion ahead of baseline level thresholds. - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. - `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`. `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)` and folds pure `LevelFilter` items directly into the mask without retaining `Box` allocations. -- `Logger::level_enabled(level)` tests each dispatch's `LevelMask` with a bitwise AND before a callsite constructs a `Record`, and `Logger::enabled(&record)` evaluates dispatch masks and filters without invoking appenders. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` in `1.0`. +- `Logger::level_enabled(level)` tests each dispatch's `LevelMask` with a bitwise AND before a callsite constructs a `Record`, and `Logger::enabled(&record)` evaluates dispatch masks and filters without invoking appenders. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. - Module-level switching operates at two granularities without scanning `Record::key_values()`: subsystems that hold dedicated `Logger` instances achieve `O(1)` callsite pruning via `Logger::level_enabled`, while a shared `Logger` using `RustLogFilter` reads `Record::module_path()` in `O(1)` after passing the level mask. ## Structured Key-Values and Diagnostics -- `Record<'a>` carries `time`, `level`, `module_path`, `file`, `line`, `column`, `payload`, and a zero-allocation `KeyValues<'a>` slice without a separate `target` field. +- `Record<'a>` carries `time`, `level`, `module_path`, `file`, `line`, `column`, `payload`, and a zero-allocation `KeyValues<'a>` slice. - Synchronous paths borrow `Record<'a>`, `Key<'a>`, and `Value<'a>` on the caller stack, using `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals. Across asynchronous boundaries, `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that workers re-project via `RecordOwned::with`. -- `ValueView<'a>` is marked `#[non_exhaustive]` and implements `fmt::Display` so unhandled variants always degrade cleanly to strings. `Value::error(&'a (dyn StdError + 'static))` and `ValueView::Error(ErrorValue<'a>)` preserve full `.source()` causal chains: `Display` renders the complete chain for text consumers, borrowed views expose the underlying `dyn StdError`, and `ValueOwned` snapshots the chain as `Box<[Cow<'static, str>]>`. `KeyView` and `ValueView` also expose `as_static_str`, `to_bytes`, and `is_none` accessors alongside `From>` and `From<&'a Cow<'_, str>>` conversions. +- `Value<'a>` provides `From` conversions for scalars, strings including `Cow`, byte slices, and `Option`, alongside explicit `Value::debug`, `Value::display`, and `Value::error(&'a (dyn StdError + 'static))` constructors. `ValueView<'a>` is marked `#[non_exhaustive]` and implements `fmt::Display` so unhandled variants degrade cleanly to strings; `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors, while `ValueView::Error(ErrorValue<'a>)` preserves full `.source()` causal chains across borrowed views, text `Display`, and `Box<[Cow<'static, str>]>` snapshots in `ValueOwned`. - `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics. - `StaticDiagnostic`, `ThreadLocalDiagnostic` with RAII scope guards, and `TaskLocalDiagnostic` store `(KeyOwned, ValueOwned)`. `Diagnostic::visit` may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. From ba8d17b3e4b689c682bdfdc3fe2cc009d500d4c5 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 01:16:20 +0800 Subject: [PATCH 04/19] docs: simplify Logger::enabled to pure level check without synthetic records Unify pre-construction pruning on `Logger::enabled(level: Level) -> bool` and let `LogBridge::enabled` delegate to it directly instead of keeping a separate `Logger::enabled(&Record)` path or constructing half-populated records. Signed-off-by: tison --- DESIGN.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index dc816ed..0becf9a 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -83,8 +83,8 @@ enum DiagnosticsInner<'a> { - `Accept` short-circuits remaining filters in the current `Dispatch` and accepts the record immediately, supporting context-driven dynamic promotion ahead of baseline level thresholds. - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. - `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`. `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)` and folds pure `LevelFilter` items directly into the mask without retaining `Box` allocations. -- `Logger::level_enabled(level)` tests each dispatch's `LevelMask` with a bitwise AND before a callsite constructs a `Record`, and `Logger::enabled(&record)` evaluates dispatch masks and filters without invoking appenders. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. -- Module-level switching operates at two granularities without scanning `Record::key_values()`: subsystems that hold dedicated `Logger` instances achieve `O(1)` callsite pruning via `Logger::level_enabled`, while a shared `Logger` using `RustLogFilter` reads `Record::module_path()` in `O(1)` after passing the level mask. +- `Logger::enabled(level)` tests each dispatch's `LevelMask` with a bitwise AND before a callsite constructs a `Record`. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. +- Module-level switching operates at two granularities without scanning `Record::key_values()`: subsystems that hold dedicated `Logger` instances achieve `O(1)` callsite pruning via `Logger::enabled(level)`, while a shared `Logger` using `RustLogFilter` reads `Record::module_path()` in `O(1)` after passing the level mask. ## Structured Key-Values and Diagnostics @@ -111,7 +111,7 @@ logforth::info!(logger, ["jobs.completed" = count]); ``` - Structured fields precede the format string using bracketed assignment expressions. Every macro argument is a valid Rust `ast::Expr` so `rustfmt` formats the entire invocation without colliding with `format_args!` named parameters. -- `$logger` and `$level` evaluate once. When `logger.level_enabled(level)` succeeds, value expressions evaluate at most once and bind shared references before constructing `!Send` `Value<'_>` or `fmt::Arguments<'_>` temporaries, keeping enclosing `async` futures `Send` across `.await` points inside log arguments. +- `$logger` and `$level` evaluate once. When `logger.enabled(level)` succeeds, value expressions evaluate at most once and bind shared references before constructing `!Send` `Value<'_>` or `fmt::Arguments<'_>` temporaries, keeping enclosing `async` futures `Send` across `.await` points inside log arguments. - String literal keys and identifier shorthands expand to `Key::new` with `'static` provenance, and record construction delegates to a non-generic `__private_log` helper backed by a `static` callsite location descriptor. `Level::Fatal` records severity metadata only and neither flushes nor terminates the process. ## Ecosystem Interop and Bridges @@ -124,7 +124,7 @@ Logforth provides bidirectional adapters for `log` and `tracing` so applications | Inbound (`tracing` -> `logforth`) | `logforth-bridge-tracing` | Implements `tracing_subscriber::Layer`, translating `tracing::Event` fields and flattening active `event_scope()` span attributes into `Record` | | Outbound (`logforth` -> `log`/`tracing`) | `logforth-append-log` | Implements `Append` by forwarding `Record` and `Diagnostics` to `log::logger()`, supporting both `log` hosts and `tracing-log` hosts | -- `LogBridge::enabled` checks `Logger::level_enabled` first and falls back to `Logger::enabled` with a stack-allocated `Record` carrying the metadata module path when callers invoke `log::log_enabled!`. +- `LogBridge::enabled` delegates directly to `Logger::enabled` on the mapped severity level without constructing a synthetic `Record`. - Libraries adopting `logforth` natively can accept an injected `Logger` whose default routes to `logforth-append-log` or `Logger::noop()`, remaining observable inside host applications that use another subscriber. - If `LogBridge` is installed as the global `log` logger while a dispatch also attaches `logforth-append-log`, a panic-safe thread-local guard set by `logforth-append-log` and checked at `LogBridge` entry breaks the cycle, drops the reentrant record, and reports the misconfiguration once via `ErrorSink`. From 324d3207576d51f2902361b2730d794efb5e465d Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 01:24:09 +0800 Subject: [PATCH 05/19] docs: drop ValueView::Error special case from DESIGN.md Keep `kv` primitives orthogonal and let callers format causal error chains with their own wrapper types rather than baking an opinionated error value variant into `logforth-core`. Signed-off-by: tison --- DESIGN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESIGN.md b/DESIGN.md index 0becf9a..55a4d21 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -90,7 +90,7 @@ enum DiagnosticsInner<'a> { - `Record<'a>` carries `time`, `level`, `module_path`, `file`, `line`, `column`, `payload`, and a zero-allocation `KeyValues<'a>` slice. - Synchronous paths borrow `Record<'a>`, `Key<'a>`, and `Value<'a>` on the caller stack, using `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals. Across asynchronous boundaries, `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that workers re-project via `RecordOwned::with`. -- `Value<'a>` provides `From` conversions for scalars, strings including `Cow`, byte slices, and `Option`, alongside explicit `Value::debug`, `Value::display`, and `Value::error(&'a (dyn StdError + 'static))` constructors. `ValueView<'a>` is marked `#[non_exhaustive]` and implements `fmt::Display` so unhandled variants degrade cleanly to strings; `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors, while `ValueView::Error(ErrorValue<'a>)` preserves full `.source()` causal chains across borrowed views, text `Display`, and `Box<[Cow<'static, str>]>` snapshots in `ValueOwned`. +- `Value<'a>` provides `From` conversions for scalars, strings including `Cow`, byte slices, and `Option`, alongside explicit `Value::debug` and `Value::display` constructors. `ValueView<'a>` is marked `#[non_exhaustive]` and implements `fmt::Display` so unhandled variants degrade cleanly to strings, while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. - `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics. - `StaticDiagnostic`, `ThreadLocalDiagnostic` with RAII scope guards, and `TaskLocalDiagnostic` store `(KeyOwned, ValueOwned)`. `Diagnostic::visit` may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. From 60025d180c9fae4091d1d7c4da6cf8371c914e23 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 01:26:41 +0800 Subject: [PATCH 06/19] docs: specify per-handle Logger level gates and RustLogFilter composition Define `Logger` as a lightweight `Clone` handle over a shared pipeline with static or `Arc` per-handle level gates so derived module or subsystem handles share dispatches and `flush` while achieving `O(1)` callsite pruning. Keep `RustLogFilter` strictly `O(1)` on `Record::module_path()` and expose its directive matcher for custom filters rather than adding KV-scanning options. Signed-off-by: tison --- DESIGN.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 55a4d21..61a37f3 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -17,7 +17,7 @@ Logforth separates three concerns into distinct primitives: | Channel (`Logger`) | Which reliability, schema, and lifecycle stream owns it? | Explicit `Logger` instances | | Fan-out (`Dispatch`) | Which output slices and destinations receive this stream? | Ordered `Dispatch` branches inside a `Logger` | -- `Logger` owns a `Vec` and a fallback `ErrorSink` without a global singleton in `logforth-core`. Callers share a `Logger` explicitly via `&Logger`, `Arc`, or `&'static Logger`, and libraries accepting an optional logger can default to a zero-allocation `const fn Logger::noop()`. +- `Logger` is a lightweight `Clone` handle backed by a shared pipeline and an inline per-handle level gate, without a global singleton in `logforth-core`. Libraries accepting an optional logger can default to a zero-allocation `const fn Logger::noop()`, and derived handles created with static or atomic `LevelMask` gates share the same underlying dispatches and `flush` lifecycle while enforcing independent `O(1)` callsite thresholds. - All five component traits (`Append`, `Layout`, `Filter`, `Diagnostic`, and `ErrorSink`) implement forwarding for `Arc` and `&'static T`. Multiple dispatches or independent `Logger` instances can share stateful components as a directed acyclic graph without a separate provider wrapper. - Configuration placement follows each component's role in the pipeline. `LoggerBuilder::error_sink` sets the logger-wide failure fallback, and `DispatchBuilder::error_sink` optionally overrides it for a specific branch. Out-of-band executors such as `Async` manage an independent worker lifecycle and configure their own `ErrorSink`. `Filter` and `Diagnostic` are configured on `DispatchBuilder` because branches within a `Logger` exist to select distinct event subsets and context; branches that share a filter or diagnostic share it explicitly via `Arc`. @@ -83,8 +83,10 @@ enum DiagnosticsInner<'a> { - `Accept` short-circuits remaining filters in the current `Dispatch` and accepts the record immediately, supporting context-driven dynamic promotion ahead of baseline level thresholds. - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. - `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`. `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)` and folds pure `LevelFilter` items directly into the mask without retaining `Box` allocations. -- `Logger::enabled(level)` tests each dispatch's `LevelMask` with a bitwise AND before a callsite constructs a `Record`. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. -- Module-level switching operates at two granularities without scanning `Record::key_values()`: subsystems that hold dedicated `Logger` instances achieve `O(1)` callsite pruning via `Logger::enabled(level)`, while a shared `Logger` using `RustLogFilter` reads `Record::module_path()` in `O(1)` after passing the level mask. +- `Logger::enabled(level)` tests the handle's level gate and the underlying dispatches' `LevelMask` union with bitwise AND operations before a callsite constructs a `Record`. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. +- Module-level switching operates at two granularities without scanning `Record::key_values()`: + 1. Per-subsystem or per-module `Logger` handles, passed explicitly or cached in a module `LazyLock` resolved once at initialization, achieve `O(1)` callsite pruning with zero string matching; dynamic reconfiguration updates each handle's `Arc` on the cold control path. + 2. A single shared `Logger` paired with `RustLogFilter` reads `Record::module_path()` in `O(1)` after passing the level mask, and `RustLogFilter` exposes a module-matching method so custom filters can compose directive matching on arbitrary fields without adding KV-scanning options to `RustLogFilter`. ## Structured Key-Values and Diagnostics @@ -131,4 +133,4 @@ Logforth provides bidirectional adapters for `log` and `tracing` so applications ## Registry Boundary - `logforth-core` omits a global named logger registry to avoid initialization-order races, ambiguous shutdown and flush ownership, and configuration-driven dependency fan-in, as crates on crates.io cannot assume a `logforth` registry exists. -- Applications requiring configuration-driven named routing, acquisition-time `O(1)` module level resolution, or runtime reconfiguration layer an optional external `logforth-registry` crate atop `logforth-core`'s public primitives (`Arc`, `Arc` component sharing, and atomic pointer swaps). Any registry requirement that cannot be expressed through public `logforth-core` traits indicates a missing composable primitive rather than a reason to embed a registry in `core`. +- Applications requiring configuration-driven named routing, acquisition-time `O(1)` module level resolution, or runtime reconfiguration layer an optional external `logforth-registry` crate atop `logforth-core`'s public primitives (`Logger` handle derivation, `Arc`, `Arc` component sharing, and atomic pointer swaps). Any registry requirement that cannot be expressed through public `logforth-core` traits indicates a missing composable primitive rather than a reason to embed a registry in `core`. From 8104548ccc4477cb034cae0453bbdf6204fbf44e Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 01:28:21 +0800 Subject: [PATCH 07/19] docs: rename DiagnosticsInner to DiagnosticsState in DESIGN.md Align the private backing enum name of `Diagnostics` with `ValueState`, `MapValueState`, and `ListValueState` in `logforth-core`. Signed-off-by: tison --- DESIGN.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 61a37f3..f63ab21 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -55,10 +55,10 @@ pub trait ErrorSink: fmt::Debug + Send + Sync + 'static { ```rust #[derive(Clone, Copy)] -pub struct Diagnostics<'a>(DiagnosticsInner<'a>); +pub struct Diagnostics<'a>(DiagnosticsState<'a>); #[derive(Clone, Copy)] -enum DiagnosticsInner<'a> { +enum DiagnosticsState<'a> { Empty, // Borrows a Dispatch's owned diagnostic list without copying or re-boxing. Boxed(&'a [Box]), From 046e7e84c0a2b22267994a09eaa32ff0a00e7f35 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 01:29:35 +0800 Subject: [PATCH 08/19] docs: confine legacy target handling to inbound log and tracing bridges Document in Ecosystem Interop that inbound `log` and `tracing` adapters populate `Record::module_path` and only emit a `"target"` key-value pair when an upstream event explicitly overrides `target`, removing negative phrasing elsewhere. Signed-off-by: tison --- DESIGN.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index f63ab21..178e5e7 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -122,11 +122,11 @@ Logforth provides bidirectional adapters for `log` and `tracing` so applications | Direction | Crate | Role | | :--------------------------------------- | :------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------- | -| Inbound (`log` -> `logforth`) | `logforth-bridge-log` | Implements `log::Log`, mapping `log::Record::target()` to `Record::module_path` and setting `log::set_max_level` from `Logger`'s `LevelMask` | +| Inbound (`log` -> `logforth`) | `logforth-bridge-log` | Implements `log::Log`, forwarding structured key-values and setting `log::set_max_level` from `Logger`'s `LevelMask` | | Inbound (`tracing` -> `logforth`) | `logforth-bridge-tracing` | Implements `tracing_subscriber::Layer`, translating `tracing::Event` fields and flattening active `event_scope()` span attributes into `Record` | | Outbound (`logforth` -> `log`/`tracing`) | `logforth-append-log` | Implements `Append` by forwarding `Record` and `Diagnostics` to `log::logger()`, supporting both `log` hosts and `tracing-log` hosts | -- `LogBridge::enabled` delegates directly to `Logger::enabled` on the mapped severity level without constructing a synthetic `Record`. +- Inbound `log` and `tracing` bridges populate `Record::module_path` from the event's module path and emit a `"target"` key-value entry only when the upstream caller explicitly overrode `target` to differ from `module_path`. `LogBridge::enabled` delegates directly to `Logger::enabled` on the mapped severity level. - Libraries adopting `logforth` natively can accept an injected `Logger` whose default routes to `logforth-append-log` or `Logger::noop()`, remaining observable inside host applications that use another subscriber. - If `LogBridge` is installed as the global `log` logger while a dispatch also attaches `logforth-append-log`, a panic-safe thread-local guard set by `logforth-append-log` and checked at `LogBridge` entry breaks the cycle, drops the reentrant record, and reports the misconfiguration once via `ErrorSink`. From be3ea7e7cf560cde77cd253a6f3ddb1313fb9e8d Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 01:31:52 +0800 Subject: [PATCH 09/19] docs: drop negative phrasing for unchosen alternatives in DESIGN.md State component sharing and module-level filtering directly instead of referencing nonexistent provider wrappers or key-value scanning options. Signed-off-by: tison --- DESIGN.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 178e5e7..5ff2255 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -18,7 +18,7 @@ Logforth separates three concerns into distinct primitives: | Fan-out (`Dispatch`) | Which output slices and destinations receive this stream? | Ordered `Dispatch` branches inside a `Logger` | - `Logger` is a lightweight `Clone` handle backed by a shared pipeline and an inline per-handle level gate, without a global singleton in `logforth-core`. Libraries accepting an optional logger can default to a zero-allocation `const fn Logger::noop()`, and derived handles created with static or atomic `LevelMask` gates share the same underlying dispatches and `flush` lifecycle while enforcing independent `O(1)` callsite thresholds. -- All five component traits (`Append`, `Layout`, `Filter`, `Diagnostic`, and `ErrorSink`) implement forwarding for `Arc` and `&'static T`. Multiple dispatches or independent `Logger` instances can share stateful components as a directed acyclic graph without a separate provider wrapper. +- All five component traits (`Append`, `Layout`, `Filter`, `Diagnostic`, and `ErrorSink`) implement forwarding for `Arc` and `&'static T`, allowing multiple dispatches or independent `Logger` instances to share stateful components directly as a directed acyclic graph. - Configuration placement follows each component's role in the pipeline. `LoggerBuilder::error_sink` sets the logger-wide failure fallback, and `DispatchBuilder::error_sink` optionally overrides it for a specific branch. Out-of-band executors such as `Async` manage an independent worker lifecycle and configure their own `ErrorSink`. `Filter` and `Diagnostic` are configured on `DispatchBuilder` because branches within a `Logger` exist to select distinct event subsets and context; branches that share a filter or diagnostic share it explicitly via `Arc`. For example, an application can isolate `audit` events on a dedicated `Logger` while its main diagnostic `Logger` fans out `Warn` records to standard error and `Debug` records to a shared `Arc`. @@ -84,9 +84,9 @@ enum DiagnosticsState<'a> { - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. - `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`. `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)` and folds pure `LevelFilter` items directly into the mask without retaining `Box` allocations. - `Logger::enabled(level)` tests the handle's level gate and the underlying dispatches' `LevelMask` union with bitwise AND operations before a callsite constructs a `Record`. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. -- Module-level switching operates at two granularities without scanning `Record::key_values()`: +- Module-level switching operates at two granularities: 1. Per-subsystem or per-module `Logger` handles, passed explicitly or cached in a module `LazyLock` resolved once at initialization, achieve `O(1)` callsite pruning with zero string matching; dynamic reconfiguration updates each handle's `Arc` on the cold control path. - 2. A single shared `Logger` paired with `RustLogFilter` reads `Record::module_path()` in `O(1)` after passing the level mask, and `RustLogFilter` exposes a module-matching method so custom filters can compose directive matching on arbitrary fields without adding KV-scanning options to `RustLogFilter`. + 2. A single shared `Logger` paired with `RustLogFilter` matches `Record::module_path()` after passing the level mask, and `RustLogFilter` exposes its module-matching method so custom filters can reuse directive matching on arbitrary fields. ## Structured Key-Values and Diagnostics From 72361ed21e29197acdf510b50bd66977681528ef Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 01:44:49 +0800 Subject: [PATCH 10/19] docs: remove unscheduled registry design and per-handle gates from DESIGN.md Drop the speculative `Registry Boundary` section and per-handle `AtomicLevelMask` / `LazyLock` machinery from `DESIGN.md`, keeping `Logger` focused on a shared immutable pipeline with `const fn Logger::noop()`. Signed-off-by: tison --- DESIGN.md | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 5ff2255..9dfcbc8 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -17,7 +17,7 @@ Logforth separates three concerns into distinct primitives: | Channel (`Logger`) | Which reliability, schema, and lifecycle stream owns it? | Explicit `Logger` instances | | Fan-out (`Dispatch`) | Which output slices and destinations receive this stream? | Ordered `Dispatch` branches inside a `Logger` | -- `Logger` is a lightweight `Clone` handle backed by a shared pipeline and an inline per-handle level gate, without a global singleton in `logforth-core`. Libraries accepting an optional logger can default to a zero-allocation `const fn Logger::noop()`, and derived handles created with static or atomic `LevelMask` gates share the same underlying dispatches and `flush` lifecycle while enforcing independent `O(1)` callsite thresholds. +- `Logger` is a lightweight `Clone` handle over a shared immutable pipeline, with no global singleton in `logforth-core`. Applications expose process-wide channels through their own initialized statics or dependency injection, while libraries accepting an optional logger can default to a zero-allocation `const fn Logger::noop()`. - All five component traits (`Append`, `Layout`, `Filter`, `Diagnostic`, and `ErrorSink`) implement forwarding for `Arc` and `&'static T`, allowing multiple dispatches or independent `Logger` instances to share stateful components directly as a directed acyclic graph. - Configuration placement follows each component's role in the pipeline. `LoggerBuilder::error_sink` sets the logger-wide failure fallback, and `DispatchBuilder::error_sink` optionally overrides it for a specific branch. Out-of-band executors such as `Async` manage an independent worker lifecycle and configure their own `ErrorSink`. `Filter` and `Diagnostic` are configured on `DispatchBuilder` because branches within a `Logger` exist to select distinct event subsets and context; branches that share a filter or diagnostic share it explicitly via `Arc`. @@ -83,10 +83,8 @@ enum DiagnosticsState<'a> { - `Accept` short-circuits remaining filters in the current `Dispatch` and accepts the record immediately, supporting context-driven dynamic promotion ahead of baseline level thresholds. - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. - `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`. `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)` and folds pure `LevelFilter` items directly into the mask without retaining `Box` allocations. -- `Logger::enabled(level)` tests the handle's level gate and the underlying dispatches' `LevelMask` union with bitwise AND operations before a callsite constructs a `Record`. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. -- Module-level switching operates at two granularities: - 1. Per-subsystem or per-module `Logger` handles, passed explicitly or cached in a module `LazyLock` resolved once at initialization, achieve `O(1)` callsite pruning with zero string matching; dynamic reconfiguration updates each handle's `Arc` on the cold control path. - 2. A single shared `Logger` paired with `RustLogFilter` matches `Record::module_path()` after passing the level mask, and `RustLogFilter` exposes its module-matching method so custom filters can reuse directive matching on arbitrary fields. +- `Logger::enabled(level)` tests the union of its dispatches' `LevelMask` values in a single bitwise operation before a callsite constructs a `Record`. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. +- `RustLogFilter` matches `Record::module_path()` after passing the level mask, and exposes its module-matching method so custom filters can reuse directive matching on arbitrary fields. ## Structured Key-Values and Diagnostics @@ -129,8 +127,3 @@ Logforth provides bidirectional adapters for `log` and `tracing` so applications - Inbound `log` and `tracing` bridges populate `Record::module_path` from the event's module path and emit a `"target"` key-value entry only when the upstream caller explicitly overrode `target` to differ from `module_path`. `LogBridge::enabled` delegates directly to `Logger::enabled` on the mapped severity level. - Libraries adopting `logforth` natively can accept an injected `Logger` whose default routes to `logforth-append-log` or `Logger::noop()`, remaining observable inside host applications that use another subscriber. - If `LogBridge` is installed as the global `log` logger while a dispatch also attaches `logforth-append-log`, a panic-safe thread-local guard set by `logforth-append-log` and checked at `LogBridge` entry breaks the cycle, drops the reentrant record, and reports the misconfiguration once via `ErrorSink`. - -## Registry Boundary - -- `logforth-core` omits a global named logger registry to avoid initialization-order races, ambiguous shutdown and flush ownership, and configuration-driven dependency fan-in, as crates on crates.io cannot assume a `logforth` registry exists. -- Applications requiring configuration-driven named routing, acquisition-time `O(1)` module level resolution, or runtime reconfiguration layer an optional external `logforth-registry` crate atop `logforth-core`'s public primitives (`Logger` handle derivation, `Arc`, `Arc` component sharing, and atomic pointer swaps). Any registry requirement that cannot be expressed through public `logforth-core` traits indicates a missing composable primitive rather than a reason to embed a registry in `core`. From 1e35e0505d2e39fff76ea2d550d53a1ac0485ff6 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 01:53:10 +0800 Subject: [PATCH 11/19] docs: document borrowing ValueOwned into Value for custom nested structures Specify `From<&'a ValueOwned> for Value<'a>` and optional `serde`-backed `ValueOwned` construction so nested custom structures integrate cleanly into `KeyValues<'a>` as concrete value trees. Signed-off-by: tison --- DESIGN.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 9dfcbc8..5931142 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -90,8 +90,8 @@ enum DiagnosticsState<'a> { - `Record<'a>` carries `time`, `level`, `module_path`, `file`, `line`, `column`, `payload`, and a zero-allocation `KeyValues<'a>` slice. - Synchronous paths borrow `Record<'a>`, `Key<'a>`, and `Value<'a>` on the caller stack, using `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals. Across asynchronous boundaries, `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that workers re-project via `RecordOwned::with`. -- `Value<'a>` provides `From` conversions for scalars, strings including `Cow`, byte slices, and `Option`, alongside explicit `Value::debug` and `Value::display` constructors. `ValueView<'a>` is marked `#[non_exhaustive]` and implements `fmt::Display` so unhandled variants degrade cleanly to strings, while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. -- `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics. +- `Value<'a>` provides `From` conversions for scalars, strings including `Cow`, byte slices, `Option`, and `&'a ValueOwned`, alongside explicit `Value::debug` and `Value::display` constructors. `ValueView<'a>` is marked `#[non_exhaustive]` and implements `fmt::Display` so unhandled variants degrade cleanly to strings, while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. +- `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics. Custom nested structures convert into `ValueOwned` on enabled callsites (including via an optional `serde`-backed constructor when the `serde` feature is enabled) and borrow into `KeyValues<'a>` through `From<&'a ValueOwned> for Value<'a>`. - `StaticDiagnostic`, `ThreadLocalDiagnostic` with RAII scope guards, and `TaskLocalDiagnostic` store `(KeyOwned, ValueOwned)`. `Diagnostic::visit` may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. ## Error Handling and Operational Safety From 2e4d434ef53983e20448a75f29f732e20ac02624 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 02:01:19 +0800 Subject: [PATCH 12/19] docs: tighten filter pruning, formatting safety, and bridge guard contracts Address final review findings in `DESIGN.md`: - Retain `LevelFilter` items in `Dispatch` filter chains so preceding dynamic `Accept` filters cannot drop downstream level thresholds, while testing each branch's `LevelMask` in `Logger::log`. - Specify `fmt::write` fallback for infallible `Record::to_owned` and `ValueView::to_owned` snapshot conversions, and `from_serde` / `try_from_serde` error behavior. - Mark `ThreadLocalDiagnostic` scope guards `!Send` with shadowed-value restoration, and place the shared bridge reentrancy guard in `logforth-core` across both inbound bridges. Signed-off-by: tison --- DESIGN.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 5931142..3d81226 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -18,7 +18,7 @@ Logforth separates three concerns into distinct primitives: | Fan-out (`Dispatch`) | Which output slices and destinations receive this stream? | Ordered `Dispatch` branches inside a `Logger` | - `Logger` is a lightweight `Clone` handle over a shared immutable pipeline, with no global singleton in `logforth-core`. Applications expose process-wide channels through their own initialized statics or dependency injection, while libraries accepting an optional logger can default to a zero-allocation `const fn Logger::noop()`. -- All five component traits (`Append`, `Layout`, `Filter`, `Diagnostic`, and `ErrorSink`) implement forwarding for `Arc` and `&'static T`, allowing multiple dispatches or independent `Logger` instances to share stateful components directly as a directed acyclic graph. +- All five component traits (`Append`, `Layout`, `Filter`, `Diagnostic`, and `ErrorSink`) implement forwarding for `Arc` and `&'static T` across all trait methods, allowing multiple dispatches or independent `Logger` instances to share stateful components directly as a directed acyclic graph; an `Append` or `ErrorSink` must never route back into its owning `Logger`. - Configuration placement follows each component's role in the pipeline. `LoggerBuilder::error_sink` sets the logger-wide failure fallback, and `DispatchBuilder::error_sink` optionally overrides it for a specific branch. Out-of-band executors such as `Async` manage an independent worker lifecycle and configure their own `ErrorSink`. `Filter` and `Diagnostic` are configured on `DispatchBuilder` because branches within a `Logger` exist to select distinct event subsets and context; branches that share a filter or diagnostic share it explicitly via `Arc`. For example, an application can isolate `audit` events on a dedicated `Logger` while its main diagnostic `Logger` fans out `Warn` records to standard error and `Debug` records to a shared `Arc`. @@ -82,8 +82,8 @@ enum DiagnosticsState<'a> { - `Reject` drops the record immediately from the current `Dispatch`. - `Accept` short-circuits remaining filters in the current `Dispatch` and accepts the record immediately, supporting context-driven dynamic promotion ahead of baseline level thresholds. - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. -- `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`. `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)` and folds pure `LevelFilter` items directly into the mask without retaining `Box` allocations. -- `Logger::enabled(level)` tests the union of its dispatches' `LevelMask` values in a single bitwise operation before a callsite constructs a `Record`. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. +- `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`, and `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)`. +- `Logger::enabled(level)` tests the union of its dispatches' `LevelMask` values in a single bitwise operation before a callsite constructs a `Record`, and `Logger::log` tests each branch's `LevelMask` before evaluating its `Filter` chain. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. - `RustLogFilter` matches `Record::module_path()` after passing the level mask, and exposes its module-matching method so custom filters can reuse directive matching on arbitrary fields. ## Structured Key-Values and Diagnostics @@ -91,13 +91,13 @@ enum DiagnosticsState<'a> { - `Record<'a>` carries `time`, `level`, `module_path`, `file`, `line`, `column`, `payload`, and a zero-allocation `KeyValues<'a>` slice. - Synchronous paths borrow `Record<'a>`, `Key<'a>`, and `Value<'a>` on the caller stack, using `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals. Across asynchronous boundaries, `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that workers re-project via `RecordOwned::with`. - `Value<'a>` provides `From` conversions for scalars, strings including `Cow`, byte slices, `Option`, and `&'a ValueOwned`, alongside explicit `Value::debug` and `Value::display` constructors. `ValueView<'a>` is marked `#[non_exhaustive]` and implements `fmt::Display` so unhandled variants degrade cleanly to strings, while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. -- `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics. Custom nested structures convert into `ValueOwned` on enabled callsites (including via an optional `serde`-backed constructor when the `serde` feature is enabled) and borrow into `KeyValues<'a>` through `From<&'a ValueOwned> for Value<'a>`. -- `StaticDiagnostic`, `ThreadLocalDiagnostic` with RAII scope guards, and `TaskLocalDiagnostic` store `(KeyOwned, ValueOwned)`. `Diagnostic::visit` may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. +- `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics. Custom nested structures convert into `ValueOwned` on enabled callsites and borrow into `KeyValues<'a>` through `From<&'a ValueOwned> for Value<'a>`; under the optional `serde` feature, `ValueOwned::from_serde` degrades serialization errors to a diagnostic string alongside fallible `ValueOwned::try_from_serde`. +- `StaticDiagnostic`, `ThreadLocalDiagnostic` with `!Send` RAII scope guards that restore shadowed values on drop, and `TaskLocalDiagnostic` store `(KeyOwned, ValueOwned)`. `Diagnostic::visit` may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. ## Error Handling and Operational Safety - `Error` boxes its `Cow<'static, str>` message and optional `Box` cause so `Result<(), Error>` occupies a single word on hot `Visitor`, `Layout`, and `Append` return paths. -- Logging pipelines must never `panic!` or `.unwrap()` on fallible user `Display` or `Debug` implementations, out-of-range timestamps, broken pipes, closed descriptors, or log rotation failures. Leaf components return `Err(Error)` with operation-specific messages, and `RollingFileWriter` writes the current record to the active file before surfacing any rollover or cleanup error. +- Logging pipelines must never `panic!` or `.unwrap()` on fallible user `Display` or `Debug` implementations, out-of-range timestamps, broken pipes, closed descriptors, or log rotation failures. Infallible snapshot conversions (`Record::to_owned` and `ValueView::to_owned`) format via `fmt::write` and substitute a placeholder string on `fmt::Error` instead of calling `to_string()` or `format!`. Leaf components return `Err(Error)` with operation-specific messages, and `RollingFileWriter` writes the current record to the active file before surfacing any rollover or cleanup error. - User `Display` and `Debug` formatting always runs on the caller thread outside appender I/O mutexes. - `ThreadLocalDiagnostic` and `TaskLocalDiagnostic` access thread-local storage exclusively via `LocalKey::try_with` so logging from TLS destructors during thread teardown degrades to empty context instead of aborting. - `Async` workers isolate per-record dispatch with `catch_unwind`, report panics via `ErrorSink`, and avoid `.expect()` when joining worker threads in `Drop`. Because Rust does not run destructors on `static` items at process exit, global bridges require an explicit `flush()` before shutdown. @@ -120,10 +120,10 @@ Logforth provides bidirectional adapters for `log` and `tracing` so applications | Direction | Crate | Role | | :--------------------------------------- | :------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------- | -| Inbound (`log` -> `logforth`) | `logforth-bridge-log` | Implements `log::Log`, forwarding structured key-values and setting `log::set_max_level` from `Logger`'s `LevelMask` | -| Inbound (`tracing` -> `logforth`) | `logforth-bridge-tracing` | Implements `tracing_subscriber::Layer`, translating `tracing::Event` fields and flattening active `event_scope()` span attributes into `Record` | -| Outbound (`logforth` -> `log`/`tracing`) | `logforth-append-log` | Implements `Append` by forwarding `Record` and `Diagnostics` to `log::logger()`, supporting both `log` hosts and `tracing-log` hosts | +| Inbound (`log` -> `logforth`) | `logforth-bridge-log` | Implements `log::Log`, forwarding structured key-values and updating `log::set_max_level` from `Logger`'s `LevelMask` on global installation | +| Inbound (`tracing` -> `logforth`) | `logforth-bridge-tracing` | Implements `tracing_subscriber::Layer`, translating `tracing::Event` fields and flattening active `event_scope()` span attributes into `Record` | +| Outbound (`logforth` -> `log`/`tracing`) | `logforth-append-log` | Implements `Append` by forwarding `Record` and `Diagnostics` to `log::logger()`, supporting both `log` hosts and `tracing-log` hosts | - Inbound `log` and `tracing` bridges populate `Record::module_path` from the event's module path and emit a `"target"` key-value entry only when the upstream caller explicitly overrode `target` to differ from `module_path`. `LogBridge::enabled` delegates directly to `Logger::enabled` on the mapped severity level. - Libraries adopting `logforth` natively can accept an injected `Logger` whose default routes to `logforth-append-log` or `Logger::noop()`, remaining observable inside host applications that use another subscriber. -- If `LogBridge` is installed as the global `log` logger while a dispatch also attaches `logforth-append-log`, a panic-safe thread-local guard set by `logforth-append-log` and checked at `LogBridge` entry breaks the cycle, drops the reentrant record, and reports the misconfiguration once via `ErrorSink`. +- If an inbound `log` or `tracing` bridge feeds a `Logger` whose dispatch also attaches `logforth-append-log`, a panic-safe thread-local guard in `logforth-core` set by `logforth-append-log` and checked at inbound bridge entry breaks the cycle, drops the reentrant record, and reports the misconfiguration once via `ErrorSink`. From dc07c7787e4e5b86d6d20fe68ca70b253390551d Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 07:35:27 +0800 Subject: [PATCH 13/19] docs: clarify named-directive lookup on RustLogFilter for custom filters Specify that `RustLogFilter` exposes named-directive lookup so custom filters can match explicit key-value categories without prematurely triggering the global fallback directive before `module_path` matching. Signed-off-by: tison --- DESIGN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESIGN.md b/DESIGN.md index 3d81226..5e6bd6e 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -84,7 +84,7 @@ enum DiagnosticsState<'a> { - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. - `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`, and `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)`. - `Logger::enabled(level)` tests the union of its dispatches' `LevelMask` values in a single bitwise operation before a callsite constructs a `Record`, and `Logger::log` tests each branch's `LevelMask` before evaluating its `Filter` chain. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. -- `RustLogFilter` matches `Record::module_path()` after passing the level mask, and exposes its module-matching method so custom filters can reuse directive matching on arbitrary fields. +- `RustLogFilter` matches `Record::module_path()` after passing the level mask, and exposes named-directive lookup so custom filters can match explicit key-value fields before falling back to module paths. ## Structured Key-Values and Diagnostics From 34abbf50b1449b864b49bd61c99e764cc7cf46d2 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 08:00:13 +0800 Subject: [PATCH 14/19] docs: align RustLogFilter verb naming with Filter::check in DESIGN.md Use `check` consistently across `Filter::check` and `RustLogFilter`'s module and named-directive check descriptions. Signed-off-by: tison --- DESIGN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESIGN.md b/DESIGN.md index 5e6bd6e..0de2afc 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -84,7 +84,7 @@ enum DiagnosticsState<'a> { - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. - `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`, and `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)`. - `Logger::enabled(level)` tests the union of its dispatches' `LevelMask` values in a single bitwise operation before a callsite constructs a `Record`, and `Logger::log` tests each branch's `LevelMask` before evaluating its `Filter` chain. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. -- `RustLogFilter` matches `Record::module_path()` after passing the level mask, and exposes named-directive lookup so custom filters can match explicit key-value fields before falling back to module paths. +- `RustLogFilter` checks `Record::module_path()` after passing the level mask, and exposes named-directive checks so custom filters can inspect explicit key-value fields before falling back to module paths. ## Structured Key-Values and Diagnostics From a4b6de222cd27263e5bb179c10ffba2d5ab0a203 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 08:03:16 +0800 Subject: [PATCH 15/19] docs: rename Filter::check to Filter::filter in DESIGN.md Align `Filter::filter` with `Append::append` and `ErrorSink::sink`, keeping `test` reserved for boolean predicates such as `LevelFilter::test` and `LevelMask::test`. Signed-off-by: tison --- DESIGN.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 0de2afc..b7284d9 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -30,7 +30,7 @@ Every long-lived pipeline extension point is an object-safe trait (`fmt::Debug + ```rust pub trait Filter: fmt::Debug + Send + Sync + 'static { fn bounds(&self) -> FilterBounds { FilterBounds::ALL } - fn check(&self, record: &Record, diags: Diagnostics) -> FilterResult; + fn filter(&self, record: &Record, diags: Diagnostics) -> FilterResult; } pub trait Diagnostic: fmt::Debug + Send + Sync + 'static { @@ -84,7 +84,7 @@ enum DiagnosticsState<'a> { - `Neutral` expresses no decision and passes control to the next filter; a `Dispatch` accepts the record if all filters finish `Neutral`. - `LevelMask(u32)` represents any subset of the 24 levels, including non-monotonic `LevelFilter` predicates, in a single machine register. Each `Filter` reports static `may_accept` and `may_neutral` masks through `Filter::bounds`, and `DispatchBuilder::build` computes the branch `LevelMask` by backwards induction `mask = may_accept | (may_neutral & next)`. - `Logger::enabled(level)` tests the union of its dispatches' `LevelMask` values in a single bitwise operation before a callsite constructs a `Record`, and `Logger::log` tests each branch's `LevelMask` before evaluating its `Filter` chain. Attaching a leading context-driven `Accept` filter widens that branch's `LevelMask` to `ALL`, trading static level pruning for per-event context inspection on that branch; runtime-mutable filters likewise report `ALL` so dynamic updates take effect immediately. -- `RustLogFilter` checks `Record::module_path()` after passing the level mask, and exposes named-directive checks so custom filters can inspect explicit key-value fields before falling back to module paths. +- `RustLogFilter` filters on `Record::module_path()` after passing the level mask, and exposes named-directive filtering so custom filters can inspect explicit key-value fields before falling back to module paths. ## Structured Key-Values and Diagnostics From d00b2c8fec2913fe0e16b0618ca227a98b07a25b Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 08:23:43 +0800 Subject: [PATCH 16/19] docs: refine explicit KV construction, Value adapters, and macro expansion - Make `Value<'a>` `Clone` (capable of holding `ValueOwned` alongside borrowed variants) so workspace types can implement `From<&'a T> for Value<'a>` directly, while `Value::debug`, `Value::display`, and `Value::serde` cover explicit conversions without `value-bag` or sigil DSLs. - Standardize native macro key-value entries on explicit `"key" = expr` string literal keys without identifier shorthands or sigils, and specify `Send`-preserving `match` binding across `.await`. Signed-off-by: tison --- DESIGN.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index b7284d9..254d960 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -90,8 +90,8 @@ enum DiagnosticsState<'a> { - `Record<'a>` carries `time`, `level`, `module_path`, `file`, `line`, `column`, `payload`, and a zero-allocation `KeyValues<'a>` slice. - Synchronous paths borrow `Record<'a>`, `Key<'a>`, and `Value<'a>` on the caller stack, using `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals. Across asynchronous boundaries, `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that workers re-project via `RecordOwned::with`. -- `Value<'a>` provides `From` conversions for scalars, strings including `Cow`, byte slices, `Option`, and `&'a ValueOwned`, alongside explicit `Value::debug` and `Value::display` constructors. `ValueView<'a>` is marked `#[non_exhaustive]` and implements `fmt::Display` so unhandled variants degrade cleanly to strings, while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. -- `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics. Custom nested structures convert into `ValueOwned` on enabled callsites and borrow into `KeyValues<'a>` through `From<&'a ValueOwned> for Value<'a>`; under the optional `serde` feature, `ValueOwned::from_serde` degrades serialization errors to a diagnostic string alongside fallible `ValueOwned::try_from_serde`. +- `Value<'a>` (`Clone`) provides `From` conversions for scalars, strings including `Cow`, byte slices, `Option`, `ValueOwned`, and `&'a ValueOwned`, alongside explicit `Value::debug`, `Value::display`, and (under the optional `serde` feature) `Value::serde` adapters; workspace domain types can implement `From<&'a T> for Value<'a>` directly to emit either borrowed values or `ValueOwned` containers. `ValueView<'a>` is `Copy`, marked `#[non_exhaustive]`, and implements `fmt::Display` so unhandled variants degrade cleanly to strings, while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. +- `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics; under the optional `serde` feature, `Value::serde` and `ValueOwned::from_serde` serialize directly into `ValueOwned` (degrading serialization errors to a diagnostic string alongside fallible `ValueOwned::try_from_serde`). - `StaticDiagnostic`, `ThreadLocalDiagnostic` with `!Send` RAII scope guards that restore shadowed values on drop, and `TaskLocalDiagnostic` store `(KeyOwned, ValueOwned)`. `Diagnostic::visit` may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. ## Error Handling and Operational Safety @@ -106,13 +106,13 @@ enum DiagnosticsState<'a> { ```rust logforth::info!(logger, "listening on {}", addr); -logforth::info!(logger, ["port" = port, tls = true], "server started"); -logforth::info!(logger, ["jobs.completed" = count]); +logforth::info!(logger, ["port" = port, "tls" = true], "server started"); +logforth::info!(logger, ["jobs.completed" = count, "error" = Value::debug(&err)]); ``` -- Structured fields precede the format string using bracketed assignment expressions. Every macro argument is a valid Rust `ast::Expr` so `rustfmt` formats the entire invocation without colliding with `format_args!` named parameters. -- `$logger` and `$level` evaluate once. When `logger.enabled(level)` succeeds, value expressions evaluate at most once and bind shared references before constructing `!Send` `Value<'_>` or `fmt::Arguments<'_>` temporaries, keeping enclosing `async` futures `Send` across `.await` points inside log arguments. -- String literal keys and identifier shorthands expand to `Key::new` with `'static` provenance, and record construction delegates to a non-generic `__private_log` helper backed by a `static` callsite location descriptor. `Level::Fatal` records severity metadata only and neither flushes nor terminates the process. +- Structured fields precede the format string using bracketed `"key" = value` assignment expressions with string literal keys and plain Rust value expressions rather than sigils or implicit field shorthands. Every macro argument is a valid Rust `ast::Expr` so `rustfmt` formats the entire invocation without colliding with `format_args!` named parameters. +- `$logger` and `$level` evaluate once. When `logger.enabled(level)` succeeds, value and format-argument expressions evaluate at most once inside a `match` scrutinee that binds shared references (`Value::debug` and `Value::display` return typed wrappers so `T: Sync` remains `Send` until erased inside the synchronous `match` arm), keeping temporaries alive, leaving non-`Copy` locals unmoved, and keeping enclosing `async` futures `Send` across `.await` points inside log arguments. +- String literal keys expand to `Key::new` with `'static` provenance, and record construction delegates to a non-generic `__private_log` helper backed by a `static` callsite location descriptor. `Level::Fatal` records severity metadata only and neither flushes nor terminates the process. ## Ecosystem Interop and Bridges From ead03dfe6cb9e0f05d0cfc11cc85292fa95e902f Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 08:30:01 +0800 Subject: [PATCH 17/19] docs: make Value<'a> Send + Sync via Sync bounds on debug and display Require `+ Sync` on `Value::debug` and `Value::display` so `Value<'a>` itself is `Send + Sync` without extra wrapper types, working uniformly inside and outside macros across `.await` points. Signed-off-by: tison --- DESIGN.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 254d960..9d06c88 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -90,7 +90,7 @@ enum DiagnosticsState<'a> { - `Record<'a>` carries `time`, `level`, `module_path`, `file`, `line`, `column`, `payload`, and a zero-allocation `KeyValues<'a>` slice. - Synchronous paths borrow `Record<'a>`, `Key<'a>`, and `Value<'a>` on the caller stack, using `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals. Across asynchronous boundaries, `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that workers re-project via `RecordOwned::with`. -- `Value<'a>` (`Clone`) provides `From` conversions for scalars, strings including `Cow`, byte slices, `Option`, `ValueOwned`, and `&'a ValueOwned`, alongside explicit `Value::debug`, `Value::display`, and (under the optional `serde` feature) `Value::serde` adapters; workspace domain types can implement `From<&'a T> for Value<'a>` directly to emit either borrowed values or `ValueOwned` containers. `ValueView<'a>` is `Copy`, marked `#[non_exhaustive]`, and implements `fmt::Display` so unhandled variants degrade cleanly to strings, while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. +- `Value<'a>` (`Clone + Send + Sync`) provides `From` conversions for scalars, strings including `Cow`, byte slices, `Option`, `ValueOwned`, and `&'a ValueOwned`, alongside explicit `Value::debug` (`&(dyn Debug + Sync)`), `Value::display` (`&(dyn Display + Sync)`), and (under the optional `serde` feature) `Value::serde` constructors; workspace domain types can implement `From<&'a T> for Value<'a>` directly to emit either borrowed values or `ValueOwned` containers. `ValueView<'a>` is `Copy`, marked `#[non_exhaustive]`, and implements `fmt::Display` so unhandled variants degrade cleanly to strings, while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. - `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics; under the optional `serde` feature, `Value::serde` and `ValueOwned::from_serde` serialize directly into `ValueOwned` (degrading serialization errors to a diagnostic string alongside fallible `ValueOwned::try_from_serde`). - `StaticDiagnostic`, `ThreadLocalDiagnostic` with `!Send` RAII scope guards that restore shadowed values on drop, and `TaskLocalDiagnostic` store `(KeyOwned, ValueOwned)`. `Diagnostic::visit` may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. @@ -111,7 +111,7 @@ logforth::info!(logger, ["jobs.completed" = count, "error" = Value::debug(&err)] ``` - Structured fields precede the format string using bracketed `"key" = value` assignment expressions with string literal keys and plain Rust value expressions rather than sigils or implicit field shorthands. Every macro argument is a valid Rust `ast::Expr` so `rustfmt` formats the entire invocation without colliding with `format_args!` named parameters. -- `$logger` and `$level` evaluate once. When `logger.enabled(level)` succeeds, value and format-argument expressions evaluate at most once inside a `match` scrutinee that binds shared references (`Value::debug` and `Value::display` return typed wrappers so `T: Sync` remains `Send` until erased inside the synchronous `match` arm), keeping temporaries alive, leaving non-`Copy` locals unmoved, and keeping enclosing `async` futures `Send` across `.await` points inside log arguments. +- `$logger` and `$level` evaluate once. When `logger.enabled(level)` succeeds, value and format-argument expressions evaluate at most once inside a `match` scrutinee that binds shared references before constructing `!Send` `fmt::Arguments<'_>` inside the synchronous `match` arm; because `Value<'_>` itself is `Send + Sync`, temporaries stay alive, non-`Copy` locals remain unmoved, and enclosing `async` futures stay `Send` across `.await` points inside log arguments. - String literal keys expand to `Key::new` with `'static` provenance, and record construction delegates to a non-generic `__private_log` helper backed by a `static` callsite location descriptor. `Level::Fatal` records severity metadata only and neither flushes nor terminates the process. ## Ecosystem Interop and Bridges From 186259c7ce84cbd985882dc2ba7ecaf9de3c9d61 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 09:49:13 +0800 Subject: [PATCH 18/19] docs: preserve Copy on Value<'a> and polish Core Extension Traits prose - Keep `Value<'a>` strictly `Copy` as a pure borrowed carrier (including `&'a ValueOwned`), preserving the clean separation between `Value<'a>` (borrowed input), `ValueOwned` (`'static` owned), and `ValueView<'a>` (unified read-only projection). - Replace `permanent contract` with `stable contract` in `Scope and Crate Versioning`, and convert the trailing bullet list in `Core Extension Traits` into prose paragraphs consistent with the rest of the section. Signed-off-by: tison --- DESIGN.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 9d06c88..44b2b6b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -4,7 +4,7 @@ This document defines the architectural model, public contracts, and target `1.0 ## Scope and Crate Versioning -- `logforth-core` carries zero mandatory third-party dependencies. Stabilizing `logforth-core 1.0` establishes a permanent contract for `Logger`, `Record`, `kv`, and the five core extension traits without coupling SemVer stability to external SDKs. +- `logforth-core` carries zero mandatory third-party dependencies. Stabilizing `logforth-core 1.0` establishes a stable contract for `Logger`, `Record`, `kv`, and the five core extension traits without coupling SemVer stability to external SDKs. - The `logforth` umbrella facade and peripheral appenders, layouts, filters, diagnostics, and ecosystem bridges evolve on independent `0.x` tracks so external dependencies such as `opentelemetry`, `jiff`, `fastrace`, `log`, and `tracing` can upgrade at their own pace. ## Pipeline Topology and Assembly @@ -69,11 +69,9 @@ enum DiagnosticsState<'a> { } ``` -- `Append` consumes structured `&Record` and `Diagnostics` directly so protocol-native sinks can encode typed fields without intermediate text serialization, whereas byte-stream sinks compose a `Layout` internally. -- `Layout::format` appends formatted bytes into a caller-supplied `&mut Vec`: - 1. Implementations must only append to `buf` without clearing or reading prior bytes, and callers must truncate `buf` back to its starting length on `Err`. - 2. Record framing such as a trailing newline belongs to the owning `Append`, not `Layout`. - 3. Synchronous appenders may pool thread-local `Vec` buffers outside I/O locks via `try_borrow_mut`, falling back to a fresh `Vec` if user `Display::fmt` logs reentrantly. +`Append` consumes structured `&Record` and `Diagnostics` directly so protocol-native sinks can encode typed fields without intermediate text serialization, whereas byte-stream sinks compose a `Layout` internally. + +`Layout::format` appends formatted bytes into a caller-supplied `&mut Vec` rather than allocating a new buffer per record. Implementations must only append to `buf` without clearing or reading prior bytes, callers must truncate `buf` back to its starting length on `Err`, and record framing such as a trailing newline belongs to the owning `Append` rather than `Layout`. Synchronous appenders may pool thread-local `Vec` buffers outside I/O locks via `try_borrow_mut`, falling back to a fresh `Vec` if user `Display::fmt` logs reentrantly. ## Filtering and Fast-Path Pruning @@ -90,8 +88,8 @@ enum DiagnosticsState<'a> { - `Record<'a>` carries `time`, `level`, `module_path`, `file`, `line`, `column`, `payload`, and a zero-allocation `KeyValues<'a>` slice. - Synchronous paths borrow `Record<'a>`, `Key<'a>`, and `Value<'a>` on the caller stack, using `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals. Across asynchronous boundaries, `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that workers re-project via `RecordOwned::with`. -- `Value<'a>` (`Clone + Send + Sync`) provides `From` conversions for scalars, strings including `Cow`, byte slices, `Option`, `ValueOwned`, and `&'a ValueOwned`, alongside explicit `Value::debug` (`&(dyn Debug + Sync)`), `Value::display` (`&(dyn Display + Sync)`), and (under the optional `serde` feature) `Value::serde` constructors; workspace domain types can implement `From<&'a T> for Value<'a>` directly to emit either borrowed values or `ValueOwned` containers. `ValueView<'a>` is `Copy`, marked `#[non_exhaustive]`, and implements `fmt::Display` so unhandled variants degrade cleanly to strings, while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. -- `ValueOwned` stores `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics; under the optional `serde` feature, `Value::serde` and `ValueOwned::from_serde` serialize directly into `ValueOwned` (degrading serialization errors to a diagnostic string alongside fallible `ValueOwned::try_from_serde`). +- `Value<'a>` (`Copy + Send + Sync`) is a lightweight borrowed carrier providing `From` conversions for scalars, strings including `Cow`, byte slices, `Option`, and `&'a ValueOwned`, alongside explicit `Value::debug` (`&(dyn Debug + Sync)`) and `Value::display` (`&(dyn Display + Sync)`) constructors; workspace types borrowing internal state can implement `From<&'a T> for Value<'a>` directly. `ValueView<'a>` (`Copy`, `#[non_exhaustive]`) unifies read-only projection across both `Value<'a>` and `ValueOwned`, implementing `fmt::Display` so unhandled variants degrade cleanly to strings while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. +- `ValueOwned` (`Clone + Send + Sync + 'static`) owns heap-backed values (`Cow<'static, str>`, `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>`) for asynchronous snapshots, diagnostics, and nested structures that cannot be borrowed directly. On enabled callsites, nested custom types construct a temporary `ValueOwned` (via custom methods or, under the optional `serde` feature, `ValueOwned::from_serde` degrading errors to a diagnostic string alongside fallible `ValueOwned::try_from_serde`) and borrow into `KeyValues<'a>` at zero copy cost via `From<&'a ValueOwned> for Value<'a>`. - `StaticDiagnostic`, `ThreadLocalDiagnostic` with `!Send` RAII scope guards that restore shadowed values on drop, and `TaskLocalDiagnostic` store `(KeyOwned, ValueOwned)`. `Diagnostic::visit` may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. ## Error Handling and Operational Safety From 6e7f7464b6397c7ad1903027922ae3b7a1af4b9a Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 25 Nov 2026 10:02:50 +0800 Subject: [PATCH 19/19] docs: tighten parenthetical prose in kv and safety sections of DESIGN.md Streamline parenthetical clauses in `Structured Key-Values and Diagnostics` and `Error Handling and Operational Safety` for consistent declarative prose across the document. Signed-off-by: tison --- DESIGN.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 44b2b6b..64a3b35 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -88,14 +88,14 @@ enum DiagnosticsState<'a> { - `Record<'a>` carries `time`, `level`, `module_path`, `file`, `line`, `column`, `payload`, and a zero-allocation `KeyValues<'a>` slice. - Synchronous paths borrow `Record<'a>`, `Key<'a>`, and `Value<'a>` on the caller stack, using `RefStr<'a>` to distinguish ephemeral `&'a str` borrows from zero-copy `&'static str` literals. Across asynchronous boundaries, `Record::to_owned()` promotes records into `'static + Send` `RecordOwned`, `KeyOwned`, and `ValueOwned` snapshots that workers re-project via `RecordOwned::with`. -- `Value<'a>` (`Copy + Send + Sync`) is a lightweight borrowed carrier providing `From` conversions for scalars, strings including `Cow`, byte slices, `Option`, and `&'a ValueOwned`, alongside explicit `Value::debug` (`&(dyn Debug + Sync)`) and `Value::display` (`&(dyn Display + Sync)`) constructors; workspace types borrowing internal state can implement `From<&'a T> for Value<'a>` directly. `ValueView<'a>` (`Copy`, `#[non_exhaustive]`) unifies read-only projection across both `Value<'a>` and `ValueOwned`, implementing `fmt::Display` so unhandled variants degrade cleanly to strings while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. -- `ValueOwned` (`Clone + Send + Sync + 'static`) owns heap-backed values (`Cow<'static, str>`, `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>`) for asynchronous snapshots, diagnostics, and nested structures that cannot be borrowed directly. On enabled callsites, nested custom types construct a temporary `ValueOwned` (via custom methods or, under the optional `serde` feature, `ValueOwned::from_serde` degrading errors to a diagnostic string alongside fallible `ValueOwned::try_from_serde`) and borrow into `KeyValues<'a>` at zero copy cost via `From<&'a ValueOwned> for Value<'a>`. +- `Value<'a>` is a `Copy + Send + Sync` borrowed carrier providing `From` conversions for scalars, strings including `Cow`, byte slices, `Option`, and `&'a ValueOwned`, alongside `Value::debug` and `Value::display` constructors over `Sync` references; workspace types borrowing internal state can implement `From<&'a T> for Value<'a>` directly. `ValueView<'a>` is a `Copy`, `#[non_exhaustive]` enum that unifies read-only projection across `Value<'a>` and `ValueOwned`, implementing `fmt::Display` so unhandled variants degrade cleanly to strings while `KeyView` and `ValueView` expose typed scalar, byte, container, and `'static` string accessors. +- `ValueOwned` is `'static + Send + Sync` and stores `Cow<'static, str>`, `Box<[u8]>`, `Box<[ValueOwned]>`, and insertion-ordered `Box<[(KeyOwned, ValueOwned)]>` slices so synchronous and asynchronous paths preserve identical field ordering and duplicate-key semantics. On enabled callsites, nested structures that cannot be borrowed directly construct a temporary `ValueOwned` via custom constructors or the optional `serde` feature's `ValueOwned::from_serde` and `ValueOwned::try_from_serde`, then borrow into `KeyValues<'a>` through `From<&'a ValueOwned> for Value<'a>`. - `StaticDiagnostic`, `ThreadLocalDiagnostic` with `!Send` RAII scope guards that restore shadowed values on drop, and `TaskLocalDiagnostic` store `(KeyOwned, ValueOwned)`. `Diagnostic::visit` may run multiple times per record and must remain side-effect-free; when keys collide in map-based outputs, explicit `Record` key-values take precedence over `Diagnostic` entries. ## Error Handling and Operational Safety - `Error` boxes its `Cow<'static, str>` message and optional `Box` cause so `Result<(), Error>` occupies a single word on hot `Visitor`, `Layout`, and `Append` return paths. -- Logging pipelines must never `panic!` or `.unwrap()` on fallible user `Display` or `Debug` implementations, out-of-range timestamps, broken pipes, closed descriptors, or log rotation failures. Infallible snapshot conversions (`Record::to_owned` and `ValueView::to_owned`) format via `fmt::write` and substitute a placeholder string on `fmt::Error` instead of calling `to_string()` or `format!`. Leaf components return `Err(Error)` with operation-specific messages, and `RollingFileWriter` writes the current record to the active file before surfacing any rollover or cleanup error. +- Logging pipelines must never `panic!` or `.unwrap()` on fallible user `Display` or `Debug` implementations, out-of-range timestamps, broken pipes, closed descriptors, or log rotation failures. Infallible snapshot conversions such as `Record::to_owned` and `ValueView::to_owned` format via `fmt::write` and substitute a placeholder string on `fmt::Error` instead of calling `to_string()` or `format!`. Leaf components return `Err(Error)` with operation-specific messages, and `RollingFileWriter` writes the current record to the active file before surfacing any rollover or cleanup error. - User `Display` and `Debug` formatting always runs on the caller thread outside appender I/O mutexes. - `ThreadLocalDiagnostic` and `TaskLocalDiagnostic` access thread-local storage exclusively via `LocalKey::try_with` so logging from TLS destructors during thread teardown degrades to empty context instead of aborting. - `Async` workers isolate per-record dispatch with `catch_unwind`, report panics via `ErrorSink`, and avoid `.expect()` when joining worker threads in `Drop`. Because Rust does not run destructors on `static` items at process exit, global bridges require an explicit `flush()` before shutdown.