Skip to content

Explore shared-sink flush deduplication and multi-logger topology ergonomics #328

Done

Description

@tisonkun

Context

Following #276, Logforth models subsystem channels (for example, general, query, background, and metering) as explicit Logger values that share stateful sinks through Arc<T> (impl<T: Append + ?Sized> Append for Arc<T>).

When an application wires M channel loggers across N shared sinks (stderr, rolling file, trace event sink, OTLP log exporter) with per-(channel, sink) severity filters and channel-specific StaticDiagnostic or InstrumentationScope metadata, two operational and ergonomic questions arise around flush() lifecycle and builder wiring.

Current Friction

  1. Redundant Append::flush() calls on shared sinks: Logger::flush() iterates over every Dispatch and invokes Append::flush() on every Box<dyn Append> without deduplicating shared Arc<T> or &'static T instances:
    • Within a single Logger that attaches the same Arc<A> to multiple dispatch branches (for example, branches with distinct filters or diagnostics), logger.flush() flushes A once per branch.
    • Across M channel Loggers sharing the same Arc<A>, calling .flush() on every logger flushes each underlying file writer or OTLP batch exporter M times. Avoiding redundant flushes currently relies on implicit caller conventions, such as registering every shared sink onto one designated primary logger (even with LevelFilter::Off) so a single primary.flush() reaches all sinks.
    • Even with that workaround, distinct Append instances that share a deeper SDK handle (such as two OpentelemetryLog appenders with different InstrumentationScopes backed by the same SdkLoggerProvider) still trigger duplicate provider.force_flush() calls unless managed directly through the provider on shutdown.
  2. Repetitive M × N dispatch assembly: Wiring M channel loggers across N optional sinks typically builds M × N Dispatch branches with identical diagnostic chains (FastraceDiagnostic, StaticDiagnostic) and differing only in the per-channel Filter.

Candidate Directions

1. Shared-sink deduplication in Logger::flush() and multi-logger flush_all

  • Append already requires 'static. A provided default method on Append (for example returning an opaque sink identity derived from (TypeId::of::<Self>(), std::ptr::from_ref(self).addr()), forwarded through Arc<T> and &'static T via (**self)) would allow:
    • Logger::flush(&self) to flush each shared Arc<T> or &'static T sink at most once across its own dispatches;
    • an optional Logger::flush_all<'a>(loggers: impl IntoIterator<Item = &'a Logger>) helper to flush a group of channel loggers in a single deduplicated pass without requiring dummy LevelFilter::Off dispatches on a primary logger.
  • Tradeoffs and limits:
    • A small local Vec of seen identities during flush() adds negligible overhead on cold flush paths while keeping log() completely untouched.
    • Pointer-level Append identity cleanly deduplicates Arc<File>, Arc<Async>, and shared Arc<OpentelemetryLog> sinks, whereas distinct OpentelemetryLog instances sharing an SdkLoggerProvider (with different InstrumentationScopes) would still flush per OpentelemetryLog unless Append exposes an explicit flush-group key or callers manage SdkLoggerProvider::force_flush / shutdown directly.

2. Multi-logger assembly ergonomics

  • Evaluate whether small builder conveniences for applying a shared diagnostic/sink set across multiple Loggers pay for their API weight, or whether a plain Rust helper function in application initialization code remains clearer and more flexible (especially when one channel intentionally uses a distinct InstrumentationScope or omits trace diagnostics).

Compatibility Notes

Nothing in the current logforth-core 0.5.0 surface blocks future evolution here: Logger, LoggerBuilder, and DispatchBuilder keep their fields private (Dispatch is internal), and adding a default dyn-compatible identity method on Append (plus Logger::flush_all) is SemVer-compatible for existing Append implementations.

Activity

  1. tisonkun commented on Dec 3, 2026

    @tisonkun
    ContributorAuthor

    1. Go Ecosystem: log/slog and uber-go/zap

    Go's two dominant structured logging designs sit on opposite sides of the flush-boundary question: the standard library (log/slog) omits flush and teardown methods from both Logger and Handler, whereas uber-go/zap exposes Sync() on Logger and Core without deduplicating shared sinks.

    1.1 Standard Library: log/slog (Go 1.21+)

    slog.Logger and slog.Handler expose only emission and context-derivation methods (Enabled, Handle, WithAttrs, WithGroup); neither defines Flush() or Close().

    • Upstream rationale (golang/go#56345): During the structured logging proposal review (golang/go#56345, design document), reviewers asked how buffered or file-backed handlers (io.WriteCloser) should be flushed and closed when slog.Handler has no teardown hook (comment by @varun06). Proposal author Jonathan Amsterdam (@jba) explained why Flush was intentionally kept out of Handler (comment on golang/go#56345): adding Flush to Handler drags termination ordering and multi-owner lifecycle management into a value-cloned logging interface, which is better owned by main or the application assembly layer that constructed the underlying writer/exporter.
    • Multi-handler fan-out (golang/go#65954): The later slog.NewMultiHandler fan-out design (golang/go#65954) preserves the same boundary: composite handlers fan out Enabled, Handle, WithAttrs, and WithGroup, while flushing buffered writers or OTLP batch processors remains on the concrete sink handles retained at initialization.

    1.2 uber-go/zap (zap.Logger + zapcore.Core)

    zap includes Sync() error directly on zapcore.Core and forwards (*zap.Logger).Sync() to its root Core.

    • No deduplication across branches or loggers: zapcore.NewTee(cores...) wraps multiple Core branches in a multiCore slice whose Sync() loops over every child unconditionally (zapcore/tee.go#L90-L96 at v1.27.0):
    func (mc multiCore) Sync() error {
    	var err error
    	for i := range mc {
    		err = multierr.Append(err, mc[i].Sync())
    	}
    	return err
    }
    • Shared WriteSyncer behavior: Derived subsystem loggers (logger.Named("query"), logger.With(...)) or separate zap.New(...) instances wired to the same zapcore.WriteSyncer share the underlying sink without reference tracking. Calling Sync() on M loggers or K tee branches invokes WriteSyncer.Sync() M × K times unless the application flushes the shared WriteSyncer (or BufferedWriteSyncer.Stop()) once in main via defer. (Calling logger.Sync() indiscriminately also hits OS-specific EINVAL / ENOTTY errors on unbuffered os.Stdout/os.Stderr; see uber-go/zap#991.)

    Annotation: Mapping to Logforth

    Go Concept Logforth Counterpart Lifecycle & Flush Comparison
    *slog.Logger + external sink handle Logger + assembly-owned FlushGuard Subsystem callers only emit records; main retains concrete sink/exporter handles and flushes each once on exit.
    zapcore.NewTee multiCore.Sync() Logger::flush() iterating Dispatch items Simple single-logger convenience (defer logger.Sync()), but repeats flush() when branches/loggers share sinks.

    Takeaway: log/slog avoids shared-sink duplicate flushes by treating sink flushing as an application-assembly responsibility rather than a Logger method, whereas zap keeps Logger.Sync() as an un-deduplicated convenience for single-logger setups and relies on explicit sink ownership in main when WriteSyncers are shared.

  2. tisonkun commented on Dec 3, 2026

    @tisonkun
    ContributorAuthor

    2. Java Ecosystem: SLF4J + Logback and Apache Log4j 2

    Java applications routinely instantiate hundreds of per-class or per-module loggers (LoggerFactory.getLogger(Foo.class)) backed by a small set of shared file, console, or network appenders. Both mainstream stacks solve shared-appender flushing by separating caller-facing Logger handles from the central LoggerContext / Configuration container.

    2.1 SLF4J + Logback

    • Caller API omits lifecycle methods: org.slf4j.Logger exposes only severity-level logging predicates and emission methods; it has no flush(), close(), or stop() method (org/slf4j/Logger.java at v_2.0.17). Subsystems holding Logger references cannot accidentally flush or close shared downstream appenders.
    • Context-level teardown: In Logback, LoggerContext.stop() owns shutdown for the entire topology, resetting the logger tree and stopping registered lifecycle components and appenders in one coordinated pass (LoggerContext.java#L350-L365 at v_1.5.17).

    2.2 Apache Log4j 2

    Log4j 2 makes the separation between per-logger routing rules and unique physical appenders explicit in AbstractConfiguration:

    • Shared Appender map vs. per-logger AppenderControl wrappers: Multiple LoggerConfig nodes (each with its own filter and level) reference shared Appender instances from a central ConcurrentMap<String, Appender> appenders table through per-binding AppenderControl wrappers.
    • Deduplicated ordered shutdown: AbstractConfiguration.stop(long timeout, TimeUnit timeUnit) first detaches AppenderControl references from every LoggerConfig so new events stop entering sinks, and then iterates the deduplicated appenders.values() collection in reverse startup order so each physical Appender flushes and stops exactly once (AbstractConfiguration.java#L364-L436 at rel/2.24.3).

    Annotation: Mapping to Logforth

    Java Concept Logforth Counterpart Lifecycle & Flush Comparison
    org.slf4j.Logger / org.apache.logging.log4j.Logger Channel &'static Logger (e.g. loggers().query) Subsystem code borrows channel loggers solely to emit events and never invokes flush().
    Log4j 2 LoggerConfig + AppenderControl Logger + Dispatch wrapping Arc<A> Per-channel filters and StaticDiagnostic metadata wrap Arc clones of the same underlying Append sink.
    AbstractConfiguration.appenders on stop() Assembly-owned FlushGuard (Vec<Arc<dyn Append>>) Shutdown iterates the unique sink/provider table once rather than walking every Logger and Dispatch edge.

    Takeaway: Java frameworks never deduce unique sinks by walking the Logger -> AppenderControl graph at flush time; instead, the configuration boundary that constructs the shared appenders already holds the canonical list of unique sinks and flushes that list once during shutdown.

  3. tisonkun commented on Dec 3, 2026

    @tisonkun
    ContributorAuthor

    3. C++ Ecosystem: spdlog, Boost.Log, and Quill

    C++ logging libraries operate under explicit ownership and deterministic destruction constraints similar to Rust, and illustrate both the vector<shared_ptr<sink>> model and the split frontend/backend registry model.

    3.1 gabime/spdlog

    spdlog is the closest structural match to Logforth's Arc<Append> sharing: subsystems create multiple named spdlog::logger instances that hold std::vector<spdlog::sink_ptr> (std::shared_ptr<spdlog::sinks::sink>) pointing to the same underlying console or file sinks.

    • logger::flush() and registry::flush_all() do not deduplicate sinks: Calling logger->flush() flushes every sink_ptr attached to that logger. Even in the global registry, registry::flush_all() (invoked by spdlog::flush_every(...) and shutdown helpers) simply loops over the loggers_ map and calls l.second->flush() on each logger without tracking visited sink_ptr addresses (include/spdlog/details/registry-inl.h#L176-L181 at v1.15.1):
    SPDLOG_INLINE void registry::flush_all() {
        std::lock_guard<std::mutex> lock(flusher_mutex_);
        for (auto &l : loggers_) {
            l.second->flush();
        }
    }
    • Operational consequence: When M registered spdlog::logger channels share a single rotating file sink, flush_all() flushes that file sink M times under the sink mutex, and users coordinating graceful async teardown still rely on explicit spdlog::shutdown() / sink ownership ordering at the end of main() (see gabime/spdlog#1607).

    3.2 Boost.Log

    • Split sources::logger frontend vs. core sink list: Frontend channel/severity loggers (boost::log::sources::severity_channel_logger_mt) have no flush() method at all. Sinks register once with the central boost::log::core singleton (core::get()->add_sink(sink)), and boost::log::core::get()->flush() iterates m_sinks so each registered sink flushes once regardless of how many frontend loggers exist (src/core.cpp#L619-L638 at boost-1.87.0).

    3.3 odygrd/quill

    • Frontend SPSC queues drained by a single Backend: Multiple quill::Logger* instances carry distinct names, levels, and std::vector<std::shared_ptr<Sink>> routing targets, while one background worker owns I/O. Calling quill::Backend::stop() at shutdown drains all thread-local queues and flushes each unique active Sink once (include/quill/Backend.h#L119-L122 at v8.2.0).

    Annotation: Mapping to Logforth

    C++ Concept Logforth Counterpart Lifecycle & Flush Comparison
    spdlog::logger with vector<shared_ptr<sink>> Logger with Dispatch wrapping Arc<Append> Identical shared-ownership ergonomics; calling .flush() per logger repeats flush() on shared sinks.
    Boost.Log m_sinks / Quill Backend::stop() RAII FlushGuard returned by logging::init() Keeping unique sink/provider handles in an initialization guard gives deterministic single-pass Drop flush.

    Takeaway: spdlog confirms that per-logger flush() over shared_ptr<sink> naturally repeats flushes when iterated across channel loggers, while Boost.Log and Quill avoid redundant flushes by flushing the unique sink collection at the backend/initialization boundary.

  4. tisonkun commented on Dec 3, 2026

    @tisonkun
    ContributorAuthor

    4. C# / .NET Ecosystem: Microsoft.Extensions.Logging, Serilog, and NLog

    .NET makes sink ownership and IDisposable flush lifetimes explicit in the type system, particularly when sub-loggers or category loggers borrow shared sinks.

    4.1 Microsoft.Extensions.Logging (ILogger<T> vs. ILoggerFactory)

    • Borrow-only ILogger<T>: Category loggers injected across services (ILogger<QueryEngine>, ILogger<Compactor>) expose only Log, IsEnabled, and BeginScope; they do not implement IDisposable and have no Flush() method.
    • Single-pass factory disposal: LoggerFactory owns the ProviderRegistration list (Console, OpenTelemetry, file providers). When the host DI container exits, LoggerFactory.Dispose() iterates _providerRegistrations once and disposes/flushes each unique ILoggerProvider (shouldDispose) a single time (LoggerFactory.cs#L263-L285 at v9.0.0).

    4.2 Serilog (WriteTo.Logger attemptDispose = false)

    Serilog supports sub-logger pipelines (WriteTo.Logger(...)) with per-branch filters and enrichers, and concretely addresses shared-pipeline flush/dispose hazards via explicit ownership opt-out:

    • Non-owning sub-logger wiring by default: LoggerSinkConfiguration.Logger(ILogger logger, bool attemptDispose = false, ...) defaults attemptDispose to false when attaching an existing ILogger as a sink (LoggerSinkConfiguration.cs#L201-L221 at v4.2.0). As Serilog's doc comment notes, disposing a shared sub-logger from every borrowing pipeline would prematurely tear down or redundantly flush sinks still shared by sibling pipelines.
    • Root CloseAndFlush(): Applications flush and dispose root sinks once at process exit via Log.CloseAndFlush() or await using var log = new LoggerConfiguration()...CreateLogger(); in Program.Main.

    4.3 NLog

    • Factory-level flush: NLog.Logger instances carry no Flush method; LogManager.Flush() / LogManager.Shutdown() delegates to LogFactory.Flush(), which flushes the unique configured Target instances asynchronously once per target rather than once per logger (LogFactory.cs#L609-L622 at v5.4.0).

    Annotation: Mapping to Logforth

    C# / .NET Concept Logforth Counterpart Lifecycle & Flush Comparison
    ILogger<T> + LoggerFactory.Dispose() &'static Logger channels + FlushGuard (Drop) Callers borrow channel loggers freely; the RAII guard returned to main owns unique sink/provider flush on exit.
    Serilog WriteTo.Logger(..., attemptDispose: false) Channel Loggers holding Arc clones without flushing Borrowing pipelines emit into shared sinks while leaving flush/shutdown ownership to the assembly root.

    Takeaway: .NET's IDisposable model reinforces Rust's RAII strengths: channel Loggers should act as non-owning emission handles over Arc sinks, while a dedicated RAII guard returned from initialization owns the unique sink and SDK provider handles and flushes them once on Drop.

  5. tisonkun commented on Dec 3, 2026

    @tisonkun
    ContributorAuthor

    5. Synthesis & Resolution for Logforth

    Across Go, Java, C++, and C#/.NET, logging frameworks converge on a clear structural rule whenever multiple channel or module loggers share downstream sinks:

    Stack Frontend Logger Exposes flush? Shared-Sink Deduplication Strategy
    Go log/slog, Java SLF4J/Logback/Log4j 2, C++ Boost.Log/Quill, .NET MEL/NLog No Initialization/configuration boundary (main, LoggerContext, AbstractConfiguration, LoggerFactory) retains unique sinks/providers and flushes each once on shutdown.
    Go uber-go/zap, C++ spdlog, C# Serilog, Rust logforth Yes (Sync / flush / Dispose) Logger::flush() stays a direct convenience for single-logger pipelines; multi-logger topologies retain unique sink/provider handles at the assembly boundary (FlushGuard / attemptDispose: false) rather than iterating every channel logger.

    Architectural Conclusions for logforth

    1. Keep Logger::flush() unchanged as a straightforward single-logger convenience:
      • In the common single-logger application (let logger = logforth::builder()...build();), calling logger.flush() on shutdown works without extra ceremony, matching zap.Logger.Sync() and spdlog::logger::flush().
      • Adding pointer-identity deduplication to Append (flush_id + Logger::flush_all) would expand the core Append trait surface while still failing to deduplicate distinct Append instances that share a deeper SDK runtime resource, such as multiple OpentelemetryLog appenders with per-channel InstrumentationScopes backed by one SdkLoggerProvider.
    2. Recommend assembly-owned FlushGuard for multi-logger shared-sink pipelines:
      • Where M channel Loggers (general, query, compaction, metering) share N sinks via Arc<T> or a shared SdkLoggerProvider, the initialization function already holds every unique Arc<A> sink and SDK provider handle at construction time.
      • Returning an application-owned RAII guard (FlushGuard holding Vec<Arc<dyn Append>> and/or SdkLoggerProvider) from init() flushes and shuts down every physical sink and exporter exactly once when main exits, covering both Arc-shared Appends and shared SDK providers uniformly without dummy LevelFilter::Off dispatches.
    3. Plain Rust helper functions suffice for M × N channel assembly:
      • A small local helper closure or function in application initialization code attaches shared Diagnostics and Arc sink clones while letting individual channels vary filters, StaticDiagnostic labels, or InstrumentationScopes without new LoggerBuilder combinators.

    Documentation & Examples

    Closing this exploration issue with the current logforth-core Append and Logger::flush() contracts preserved as-is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions