Repository navigation
Description
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
- Redundant
Append::flush()calls on shared sinks:Logger::flush()iterates over everyDispatchand invokesAppend::flush()on everyBox<dyn Append>without deduplicating sharedArc<T>or&'static Tinstances:- Within a single
Loggerthat attaches the sameArc<A>to multiple dispatch branches (for example, branches with distinct filters or diagnostics),logger.flush()flushesAonce per branch. - Across
MchannelLoggers sharing the sameArc<A>, calling.flush()on every logger flushes each underlying file writer or OTLP batch exporterMtimes. Avoiding redundant flushes currently relies on implicit caller conventions, such as registering every shared sink onto one designated primary logger (even withLevelFilter::Off) so a singleprimary.flush()reaches all sinks. - Even with that workaround, distinct
Appendinstances that share a deeper SDK handle (such as twoOpentelemetryLogappenders with differentInstrumentationScopes backed by the sameSdkLoggerProvider) still trigger duplicateprovider.force_flush()calls unless managed directly through the provider on shutdown.
- Within a single
- Repetitive
M × Ndispatch assembly: WiringMchannel loggers acrossNoptional sinks typically buildsM × NDispatchbranches with identical diagnostic chains (FastraceDiagnostic,StaticDiagnostic) and differing only in the per-channelFilter.
Candidate Directions
1. Shared-sink deduplication in Logger::flush() and multi-logger flush_all
Appendalready requires'static. A provided default method onAppend(for example returning an opaque sink identity derived from(TypeId::of::<Self>(), std::ptr::from_ref(self).addr()), forwarded throughArc<T>and&'static Tvia(**self)) would allow:Logger::flush(&self)to flush each sharedArc<T>or&'static Tsink 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 dummyLevelFilter::Offdispatches on a primary logger.
- Tradeoffs and limits:
- A small local
Vecof seen identities duringflush()adds negligible overhead on cold flush paths while keepinglog()completely untouched. - Pointer-level
Appendidentity cleanly deduplicatesArc<File>,Arc<Async>, and sharedArc<OpentelemetryLog>sinks, whereas distinctOpentelemetryLoginstances sharing anSdkLoggerProvider(with differentInstrumentationScopes) would still flush perOpentelemetryLogunlessAppendexposes an explicit flush-group key or callers manageSdkLoggerProvider::force_flush/shutdowndirectly.
- A small local
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 distinctInstrumentationScopeor 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
tisonkun commentedon Dec 3, 2026
1. Go Ecosystem:
log/sloganduber-go/zapGo'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 bothLoggerandHandler, whereasuber-go/zapexposesSync()onLoggerandCorewithout deduplicating shared sinks.1.1 Standard Library:
log/slog(Go 1.21+)slog.Loggerandslog.Handlerexpose only emission and context-derivation methods (Enabled,Handle,WithAttrs,WithGroup); neither definesFlush()orClose().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 whenslog.Handlerhas no teardown hook (comment by@varun06). Proposal author Jonathan Amsterdam (@jba) explained whyFlushwas intentionally kept out ofHandler(comment ongolang/go#56345): addingFlushtoHandlerdrags termination ordering and multi-owner lifecycle management into a value-cloned logging interface, which is better owned bymainor the application assembly layer that constructed the underlying writer/exporter.golang/go#65954): The laterslog.NewMultiHandlerfan-out design (golang/go#65954) preserves the same boundary: composite handlers fan outEnabled,Handle,WithAttrs, andWithGroup, 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)zapincludesSync() errordirectly onzapcore.Coreand forwards(*zap.Logger).Sync()to its rootCore.zapcore.NewTee(cores...)wraps multipleCorebranches in amultiCoreslice whoseSync()loops over every child unconditionally (zapcore/tee.go#L90-L96atv1.27.0):WriteSyncerbehavior: Derived subsystem loggers (logger.Named("query"),logger.With(...)) or separatezap.New(...)instances wired to the samezapcore.WriteSyncershare the underlying sink without reference tracking. CallingSync()onMloggers orKtee branches invokesWriteSyncer.Sync()M × Ktimes unless the application flushes the sharedWriteSyncer(orBufferedWriteSyncer.Stop()) once inmainviadefer. (Callinglogger.Sync()indiscriminately also hits OS-specificEINVAL/ENOTTYerrors on unbufferedos.Stdout/os.Stderr; seeuber-go/zap#991.)Annotation: Mapping to Logforth
*slog.Logger+ external sink handleLogger+ assembly-ownedFlushGuardmainretains concrete sink/exporter handles and flushes each once on exit.zapcore.NewTeemultiCore.Sync()Logger::flush()iteratingDispatchitemsdefer logger.Sync()), but repeatsflush()when branches/loggers share sinks.Takeaway:
log/slogavoids shared-sink duplicate flushes by treating sink flushing as an application-assembly responsibility rather than aLoggermethod, whereaszapkeepsLogger.Sync()as an un-deduplicated convenience for single-logger setups and relies on explicit sink ownership inmainwhenWriteSyncers are shared.tisonkun commentedon Dec 3, 2026
2. Java Ecosystem:
SLF4J + LogbackandApache Log4j 2Java 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-facingLoggerhandles from the centralLoggerContext/Configurationcontainer.2.1
SLF4J+Logbackorg.slf4j.Loggerexposes only severity-level logging predicates and emission methods; it has noflush(),close(), orstop()method (org/slf4j/Logger.javaatv_2.0.17). Subsystems holdingLoggerreferences cannot accidentally flush or close shared downstream appenders.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-L365atv_1.5.17).2.2
Apache Log4j 2Log4j 2makes the separation between per-logger routing rules and unique physical appenders explicit inAbstractConfiguration:Appendermap vs. per-loggerAppenderControlwrappers: MultipleLoggerConfignodes (each with its own filter and level) reference sharedAppenderinstances from a centralConcurrentMap<String, Appender> appenderstable through per-bindingAppenderControlwrappers.AbstractConfiguration.stop(long timeout, TimeUnit timeUnit)first detachesAppenderControlreferences from everyLoggerConfigso new events stop entering sinks, and then iterates the deduplicatedappenders.values()collection in reverse startup order so each physicalAppenderflushes and stops exactly once (AbstractConfiguration.java#L364-L436atrel/2.24.3).Annotation: Mapping to Logforth
org.slf4j.Logger/org.apache.logging.log4j.Logger&'static Logger(e.g.loggers().query)flush().Log4j 2LoggerConfig+AppenderControlLogger+DispatchwrappingArc<A>StaticDiagnosticmetadata wrapArcclones of the same underlyingAppendsink.AbstractConfiguration.appendersonstop()FlushGuard(Vec<Arc<dyn Append>>)LoggerandDispatchedge.Takeaway: Java frameworks never deduce unique sinks by walking the
Logger -> AppenderControlgraph 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.tisonkun commentedon Dec 3, 2026
3. C++ Ecosystem:
spdlog,Boost.Log, andQuillC++ 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/spdlogspdlogis the closest structural match to Logforth'sArc<Append>sharing: subsystems create multiple namedspdlog::loggerinstances that holdstd::vector<spdlog::sink_ptr>(std::shared_ptr<spdlog::sinks::sink>) pointing to the same underlying console or file sinks.logger::flush()andregistry::flush_all()do not deduplicate sinks: Callinglogger->flush()flushes everysink_ptrattached to that logger. Even in the global registry,registry::flush_all()(invoked byspdlog::flush_every(...)and shutdown helpers) simply loops over theloggers_map and callsl.second->flush()on each logger without tracking visitedsink_ptraddresses (include/spdlog/details/registry-inl.h#L176-L181atv1.15.1):Mregisteredspdlog::loggerchannels share a single rotating file sink,flush_all()flushes that file sinkMtimes under the sink mutex, and users coordinating graceful async teardown still rely on explicitspdlog::shutdown()/ sink ownership ordering at the end ofmain()(seegabime/spdlog#1607).3.2
Boost.Logsources::loggerfrontend vs.coresink list: Frontend channel/severity loggers (boost::log::sources::severity_channel_logger_mt) have noflush()method at all. Sinks register once with the centralboost::log::coresingleton (core::get()->add_sink(sink)), andboost::log::core::get()->flush()iteratesm_sinksso each registered sink flushes once regardless of how many frontend loggers exist (src/core.cpp#L619-L638atboost-1.87.0).3.3
odygrd/quillBackend: Multiplequill::Logger*instances carry distinct names, levels, andstd::vector<std::shared_ptr<Sink>>routing targets, while one background worker owns I/O. Callingquill::Backend::stop()at shutdown drains all thread-local queues and flushes each unique activeSinkonce (include/quill/Backend.h#L119-L122atv8.2.0).Annotation: Mapping to Logforth
spdlog::loggerwithvector<shared_ptr<sink>>LoggerwithDispatchwrappingArc<Append>.flush()per logger repeatsflush()on shared sinks.Boost.Logm_sinks/QuillBackend::stop()FlushGuardreturned bylogging::init()Dropflush.Takeaway:
spdlogconfirms that per-loggerflush()overshared_ptr<sink>naturally repeats flushes when iterated across channel loggers, whileBoost.LogandQuillavoid redundant flushes by flushing the unique sink collection at the backend/initialization boundary.tisonkun commentedon Dec 3, 2026
4. C# / .NET Ecosystem:
Microsoft.Extensions.Logging,Serilog, andNLog.NET makes sink ownership and
IDisposableflush 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)ILogger<T>: Category loggers injected across services (ILogger<QueryEngine>,ILogger<Compactor>) expose onlyLog,IsEnabled, andBeginScope; they do not implementIDisposableand have noFlush()method.LoggerFactoryowns theProviderRegistrationlist (Console,OpenTelemetry, file providers). When the host DI container exits,LoggerFactory.Dispose()iterates_providerRegistrationsonce and disposes/flushes each uniqueILoggerProvider(shouldDispose) a single time (LoggerFactory.cs#L263-L285atv9.0.0).4.2
Serilog(WriteTo.LoggerattemptDispose = false)Serilogsupports sub-logger pipelines (WriteTo.Logger(...)) with per-branch filters and enrichers, and concretely addresses shared-pipeline flush/dispose hazards via explicit ownership opt-out:LoggerSinkConfiguration.Logger(ILogger logger, bool attemptDispose = false, ...)defaultsattemptDisposetofalsewhen attaching an existingILoggeras a sink (LoggerSinkConfiguration.cs#L201-L221atv4.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.CloseAndFlush(): Applications flush and dispose root sinks once at process exit viaLog.CloseAndFlush()orawait using var log = new LoggerConfiguration()...CreateLogger();inProgram.Main.4.3
NLogNLog.Loggerinstances carry noFlushmethod;LogManager.Flush()/LogManager.Shutdown()delegates toLogFactory.Flush(), which flushes the unique configuredTargetinstances asynchronously once per target rather than once per logger (LogFactory.cs#L609-L622atv5.4.0).Annotation: Mapping to Logforth
ILogger<T>+LoggerFactory.Dispose()&'static Loggerchannels +FlushGuard(Drop)mainowns unique sink/provider flush on exit.SerilogWriteTo.Logger(..., attemptDispose: false)Loggers holdingArcclones without flushingTakeaway: .NET's
IDisposablemodel reinforces Rust's RAII strengths: channelLoggers should act as non-owning emission handles overArcsinks, while a dedicated RAII guard returned from initialization owns the unique sink and SDK provider handles and flushes them once onDrop.tisonkun commentedon Dec 3, 2026
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:
LoggerExposesflush?log/slog, JavaSLF4J/Logback/Log4j 2, C++Boost.Log/Quill, .NETMEL/NLogmain,LoggerContext,AbstractConfiguration,LoggerFactory) retains unique sinks/providers and flushes each once on shutdown.uber-go/zap, C++spdlog, C#Serilog, RustlogforthSync/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
logforthLogger::flush()unchanged as a straightforward single-logger convenience:let logger = logforth::builder()...build();), callinglogger.flush()on shutdown works without extra ceremony, matchingzap.Logger.Sync()andspdlog::logger::flush().Append(flush_id+Logger::flush_all) would expand the coreAppendtrait surface while still failing to deduplicate distinctAppendinstances that share a deeper SDK runtime resource, such as multipleOpentelemetryLogappenders with per-channelInstrumentationScopes backed by oneSdkLoggerProvider.FlushGuardfor multi-logger shared-sink pipelines:MchannelLoggers (general,query,compaction,metering) shareNsinks viaArc<T>or a sharedSdkLoggerProvider, the initialization function already holds every uniqueArc<A>sink and SDK provider handle at construction time.FlushGuardholdingVec<Arc<dyn Append>>and/orSdkLoggerProvider) frominit()flushes and shuts down every physical sink and exporter exactly once whenmainexits, covering bothArc-sharedAppends and shared SDK providers uniformly without dummyLevelFilter::Offdispatches.M × Nchannel assembly:Diagnostics andArcsink clones while letting individual channels vary filters,StaticDiagnosticlabels, orInstrumentationScopes without newLoggerBuildercombinators.Documentation & Examples
examples/src/multi_logger_pipeline.rsdemonstrating multiple subsystemLoggerchannels (OnceLock<Loggers>withLogger::noop()pre-init fallback) sharingArcsinks and flushing each unique sink once on exit via an RAIIFlushGuard, alongsideexamples/src/opentelemetry_shared_provider.rsfor sharedSdkLoggerProvidershutdown.Closing this exploration issue with the current
logforth-coreAppendandLogger::flush()contracts preserved as-is.