Skip to main content

quick_start/
quick_start.rs

1//! Minimal quick-start example for `insomnilog`.
2
3use std::{error::Error, sync::Arc};
4
5use insomnilog::{
6    ConsoleSink, LogLevel, PatternFormatter, log_debug, log_error, log_info, log_warn,
7    preallocate_thread,
8};
9
10fn main() -> Result<(), Box<dyn Error>> {
11    // 1. Start the backend worker thread. The returned guard keeps it alive;
12    // dropping it drains all buffered records and joins the thread.
13    let _guard = insomnilog::start(insomnilog::BackendOptions::default())?;
14
15    // 2. Create a sink — decides where and how records are written. The built-in
16    // `ConsoleSink` formats records as human-readable lines and writes them to
17    // stdout.
18    let sink = Arc::new(ConsoleSink::new(
19        PatternFormatter::default(),
20        LogLevel::Trace,
21    ));
22
23    // 3. Create a logger — the handle you pass to every log macro. It holds a
24    // level filter and the list of sinks that receive its records.
25    let logger = insomnilog::create_logger("app", vec![sink], LogLevel::Trace)?;
26
27    // Optional: Eagerly allocate this thread's queue so the first log call is
28    // allocation-free. Omit it and allocation happens on first use.
29    preallocate_thread();
30
31    // 4. Start logging
32    // The macros accept a format string and zero or more typed arguments, similar to
33    // `println!`
34    log_info!(logger, "application started");
35    log_debug!(logger, "config loaded from {}", "/etc/app/config.toml");
36    log_warn!(logger, "disk usage at {}%", 87.5_f64);
37    log_error!(logger, "connection lost to {}", "db-primary");
38
39    // _guard drops here → backend drains and exits cleanly.
40    Ok(())
41}