From c9dc19ab51b535b9faa73c62aed110cb3687c325 Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 3 Dec 2026 08:14:49 +0800 Subject: [PATCH 1/2] docs(examples): add multi-logger shared-sink pipeline example When an application separates diagnostics into multiple domain `Logger` channels that share `Arc` appenders, calling `flush()` on every `Logger` repeats flushes on each shared sink. Add a runnable `multi_logger_pipeline` example demonstrating how subsystems emit records through channel handles (`Logger::noop()` before initialization) while the initialization boundary returns a `FlushGuard` over the unique `Vec>` sink list so shutdown flushes each shared sink once. Signed-off-by: tison --- examples/Cargo.toml | 5 + examples/README.md | 1 + examples/src/multi_logger_pipeline.rs | 153 ++++++++++++++++++++++++++ 3 files changed, 159 insertions(+) create mode 100644 examples/src/multi_logger_pipeline.rs diff --git a/examples/Cargo.toml b/examples/Cargo.toml index e9c1773b..92555232 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -27,6 +27,7 @@ release = false fastrace = { workspace = true, features = ["enable"] } log = { workspace = true, features = ["kv_serde", "std"] } logforth = { workspace = true, features = [ + "append-async", "append-fastrace", "append-opentelemetry", "bridge-log", @@ -46,6 +47,10 @@ tokio = { workspace = true, features = ["macros", "rt", "time"] } name = "library_logger" path = "src/library_logger.rs" +[[example]] +name = "multi_logger_pipeline" +path = "src/multi_logger_pipeline.rs" + [[example]] name = "per_module_logger" path = "src/per_module_logger.rs" diff --git a/examples/README.md b/examples/README.md index 4af4bc1d..d8fe6786 100644 --- a/examples/README.md +++ b/examples/README.md @@ -11,6 +11,7 @@ cargo run -p examples --example ## How to ... * **How to accept a `Logger` in a library without requiring a global logger?** See [`library_logger.rs`](src/library_logger.rs). +* **How to coordinate multiple channel `Logger`s over shared sinks and flush each sink once?** See [`multi_logger_pipeline.rs`](src/multi_logger_pipeline.rs). * **How to give each module its own default log level while still honoring `RUST_LOG`?** See [`per_module_logger.rs`](src/per_module_logger.rs). * **How to route `log` crate records and native `logforth` events into one pipeline?** See [`log_bridge.rs`](src/log_bridge.rs). * **How to propagate request context across concurrent async tasks?** See [`task_local_context.rs`](src/task_local_context.rs). diff --git a/examples/src/multi_logger_pipeline.rs b/examples/src/multi_logger_pipeline.rs new file mode 100644 index 00000000..9fe7573e --- /dev/null +++ b/examples/src/multi_logger_pipeline.rs @@ -0,0 +1,153 @@ +// Copyright 2024 FastLabs Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! How to coordinate multiple channel `Logger`s over shared sinks and flush each sink once? +//! +//! Build the sinks once, give each channel an `Arc` clone, and keep one handle per sink in +//! a guard. Dropping the guard in `main` flushes the sinks after all subsystems finish. + +mod logging { + use std::sync::Arc; + use std::sync::OnceLock; + + use logforth::Append; + use logforth::Filter; + use logforth::Logger; + use logforth::append::Stderr; + use logforth::append::Stdout; + use logforth::append::asynchronous::AsyncBuilder; + use logforth::diagnostic::StaticDiagnostic; + use logforth::filter::rustlog::RustLogFilterBuilder; + use logforth::layout::JsonLayout; + use logforth::layout::TextLayout; + use logforth::record::Level; + use logforth::record::LevelFilter; + + pub struct Loggers { + pub general: Logger, + pub query: Logger, + pub compaction: Logger, + } + + static LOGGERS: OnceLock = OnceLock::new(); + static NOOP_LOGGERS: Loggers = Loggers { + general: Logger::noop(), + query: Logger::noop(), + compaction: Logger::noop(), + }; + + pub fn loggers() -> &'static Loggers { + LOGGERS.get().unwrap_or(&NOOP_LOGGERS) + } + + pub struct FlushGuard { + sinks: Vec>, + } + + impl FlushGuard { + pub fn flush(&self) { + for sink in &self.sinks { + if let Err(error) = sink.flush() { + eprintln!("failed to flush log sink: {error}"); + } + } + } + } + + impl Drop for FlushGuard { + fn drop(&mut self) { + self.flush(); + } + } + + pub fn init() -> Result { + fn channel_logger( + channel: &'static str, + json_filter: impl Into>, + json_sink: &Arc, + alert_sink: &Arc, + ) -> Logger { + let context = StaticDiagnostic::new([("service", "warehouse"), ("channel", channel)]); + logforth::builder() + .dispatch(|d| { + d.filter(json_filter) + .diagnostic(context.clone()) + .append(json_sink.clone()) + }) + .dispatch(|d| { + d.filter(LevelFilter::MoreSevereEqual(Level::Warn)) + .diagnostic(context) + .append(alert_sink.clone()) + }) + .build() + } + + let json_sink = Arc::new( + AsyncBuilder::new("example-json") + .append(Stdout::new().with_layout(JsonLayout::new().utc())) + .build()?, + ); + let alert_sink = Arc::new(Stderr::new().with_layout(TextLayout::new().no_color().utc())); + let general_filter = RustLogFilterBuilder::from_default_env_or("info")?.build(); + let _ = LOGGERS.set(Loggers { + general: channel_logger("general", general_filter, &json_sink, &alert_sink), + query: channel_logger( + "query", + LevelFilter::MoreSevereEqual(Level::Debug), + &json_sink, + &alert_sink, + ), + compaction: channel_logger( + "compaction", + LevelFilter::MoreSevereEqual(Level::Info), + &json_sink, + &alert_sink, + ), + }); + Ok(FlushGuard { + sinks: vec![json_sink, alert_sink], + }) + } +} + +mod query_engine { + use crate::logging::loggers; + + pub fn execute(sql: &str) { + let logger = &loggers().query; + logforth::debug!(logger, ["sql" = sql], "planning query"); + logforth::warn!(logger, ["sql" = sql, "elapsed_ms" = 1250], "slow query"); + } +} + +mod compactor { + use crate::logging::loggers; + + pub fn run_cycle(table: &str) { + logforth::info!( + loggers().compaction, + ["table" = table], + "starting compaction" + ); + } +} + +fn main() -> Result<(), logforth::Error> { + query_engine::execute("SELECT 1"); + let _guard = logging::init()?; + logforth::info!(logging::loggers().general, "warehouse started"); + query_engine::execute("SELECT count(*) FROM orders"); + compactor::run_cycle("orders"); + Ok(()) +} From a4a88916e7c2a5f32ffecc6bbe9951d9561392f1 Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 3 Dec 2026 09:11:22 +0800 Subject: [PATCH 2/2] docs(examples): clarify multi-logger pipeline steps with inline comments Add concise inline comments to `examples/src/multi_logger_pipeline.rs` explaining the pre-initialization `NOOP_LOGGERS` fallback, per-channel sink sharing, and single-pass `FlushGuard` drop behavior. Signed-off-by: tison --- examples/src/multi_logger_pipeline.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/examples/src/multi_logger_pipeline.rs b/examples/src/multi_logger_pipeline.rs index 9fe7573e..29c46a38 100644 --- a/examples/src/multi_logger_pipeline.rs +++ b/examples/src/multi_logger_pipeline.rs @@ -41,6 +41,7 @@ mod logging { } static LOGGERS: OnceLock = OnceLock::new(); + // Fallback used before `init()` so early subsystem calls drop records silently. static NOOP_LOGGERS: Loggers = Loggers { general: Logger::noop(), query: Logger::noop(), @@ -51,6 +52,7 @@ mod logging { LOGGERS.get().unwrap_or(&NOOP_LOGGERS) } + // Holds one handle per unique sink so shutdown flushes each sink once instead of per channel. pub struct FlushGuard { sinks: Vec>, } @@ -72,6 +74,7 @@ mod logging { } pub fn init() -> Result { + // Tag records with the channel name and route them to shared `Arc` clones of the sinks. fn channel_logger( channel: &'static str, json_filter: impl Into>, @@ -93,6 +96,7 @@ mod logging { .build() } + // Construct each physical sink once: async JSON on stdout, warn+ alerts on stderr. let json_sink = Arc::new( AsyncBuilder::new("example-json") .append(Stdout::new().with_layout(JsonLayout::new().utc())) @@ -144,7 +148,10 @@ mod compactor { } fn main() -> Result<(), logforth::Error> { + // Safe before `init()`: hits `NOOP_LOGGERS` and is silently discarded. query_engine::execute("SELECT 1"); + + // Dropping `_guard` on exit flushes `json_sink` and `alert_sink` once each. let _guard = logging::init()?; logforth::info!(logging::loggers().general, "warehouse started"); query_engine::execute("SELECT count(*) FROM orders");