Skip to main content

semquery_core/
verbose.rs

1//! Lightweight verbose-progress helper for timing multi-step operations.
2
3use std::sync::OnceLock;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::time::{Duration, Instant};
6
7/// Tracks whether the configured logger is already duplicating log output to
8/// the terminal. When it is not, `Verbose` falls back to `eprintln!` so that
9/// progress messages are always visible to the user.
10static LOGS_TO_TERMINAL: OnceLock<AtomicBool> = OnceLock::new();
11
12/// Tell `Verbose` whether log records are already being printed to the terminal.
13/// This should be called once by the application after the logger is initialized.
14pub fn set_log_terminal_output(enabled: bool) {
15  let _ = LOGS_TO_TERMINAL.set(AtomicBool::new(enabled));
16}
17
18fn logs_to_terminal() -> bool {
19  LOGS_TO_TERMINAL.get().map(|b| b.load(Ordering::Relaxed)).unwrap_or(false)
20}
21
22/// Emit a verbose progress message.
23///
24/// The raw message is written to the log file under the fixed `semquery` target so
25/// that it appears as `INFO [semquery] <msg>` rather than exposing the internal
26/// `semquery_core::verbose` module path. If the logger is not already duplicating
27/// output to the terminal, the message is also prefixed with `[semquery]` and
28/// printed to stderr.
29fn emit_verbose(msg: &str) {
30  log::info!(target: "semquery", "{}", msg);
31  if !logs_to_terminal() {
32    eprintln!("[semquery] {msg}");
33  }
34}
35
36/// On/off flag for verbose progress output.
37#[derive(Clone, Copy, Debug, Default)]
38pub struct Verbose(pub bool);
39
40impl Verbose {
41  pub fn enabled(&self) -> bool {
42    self.0
43  }
44
45  /// Print an informational message when verbose mode is on.
46  /// The message is always written to the log file and printed to the terminal
47  /// unless the logger is already duplicating output to the terminal.
48  pub fn log(&self, msg: &str) {
49    if self.0 {
50      emit_verbose(msg);
51    }
52  }
53
54  /// Print the elapsed time for a completed step.
55  pub fn step(&self, name: &str, elapsed: Duration) {
56    if self.0 {
57      emit_verbose(&format!("{name}: {} ms", elapsed.as_millis()));
58    }
59  }
60
61  /// Start a timed step; the time is printed when the returned `Step` is dropped.
62  pub fn start(&self, name: &'static str) -> Step {
63    Step::new(*self, name)
64  }
65}
66
67/// RAII timer for a single verbose step.
68pub struct Step {
69  verbose: Verbose,
70  name: &'static str,
71  start: Instant,
72}
73
74impl Step {
75  pub fn new(verbose: Verbose, name: &'static str) -> Self {
76    if verbose.0 {
77      emit_verbose(&format!("{name}..."));
78    }
79    Self {
80      verbose,
81      name,
82      start: Instant::now(),
83    }
84  }
85}
86
87impl Drop for Step {
88  fn drop(&mut self) {
89    self.verbose.step(self.name, self.start.elapsed());
90  }
91}