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..29c46a38 --- /dev/null +++ b/examples/src/multi_logger_pipeline.rs @@ -0,0 +1,160 @@ +// 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(); + // Fallback used before `init()` so early subsystem calls drop records silently. + 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) + } + + // Holds one handle per unique sink so shutdown flushes each sink once instead of per channel. + 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 { + // 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>, + 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() + } + + // 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())) + .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> { + // 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"); + compactor::run_cycle("orders"); + Ok(()) +}