bob/logging.rs
1/*
2 * Copyright (c) 2026 Jonathan Perkin <jonathan@perkin.org.uk>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17/*
18 * Logging infrastructure, outputs bunyan-style JSON to a logs directory.
19 */
20
21use anyhow::{Context, Result};
22use std::fs;
23use std::path::PathBuf;
24use std::sync::OnceLock;
25use tracing_appender::non_blocking::WorkerGuard;
26use tracing_subscriber::{
27 EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt,
28};
29
30static LOG_GUARD: OnceLock<WorkerGuard> = OnceLock::new();
31
32/// Initialize the logging system.
33/// Creates a logs directory and writes JSON-formatted logs there.
34pub fn init(logs_dir: &PathBuf, log_level: &str) -> Result<()> {
35 // Create logs directory
36 fs::create_dir_all(logs_dir).with_context(|| {
37 format!("Failed to create logs directory {:?}", logs_dir)
38 })?;
39
40 // Create a rolling file appender that writes to logs/bob.log
41 let file_appender = tracing_appender::rolling::never(logs_dir, "bob.log");
42 let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
43
44 // Store the guard to keep the writer alive
45 LOG_GUARD
46 .set(guard)
47 .map_err(|_| anyhow::anyhow!("Logging already initialized"))?;
48
49 // Build the subscriber with JSON formatting for files
50 let file_layer = fmt::layer()
51 .json()
52 .with_writer(non_blocking)
53 .with_target(true)
54 .with_thread_ids(false)
55 .with_thread_names(false)
56 .with_file(false)
57 .with_line_number(false)
58 .with_span_list(false);
59
60 // Set up env filter - allow RUST_LOG to override
61 let default_filter = format!("bob={}", log_level);
62 let filter = EnvFilter::try_from_default_env()
63 .unwrap_or_else(|_| EnvFilter::new(&default_filter));
64
65 tracing_subscriber::registry().with(filter).with(file_layer).init();
66
67 tracing::info!(logs_dir = %logs_dir.display(),
68 log_level = log_level,
69 "Logging initialized"
70 );
71
72 Ok(())
73}