Skip to main content

grit_lib/
net_trace.rs

1//! Lightweight, env-gated tracing for the networking paths (transport connect,
2//! fetch/push negotiation, pack transfer).
3//!
4//! Set `GRIT_NET_DEBUG=1` to print one-line `[grit-net] …` markers to stderr
5//! before, during, and after each remote operation. Off by default and
6//! essentially free when disabled (the gate is read once and the format args are
7//! not evaluated). Embedders can consult [`enabled`] to interleave their own
8//! before/after markers with the library's.
9
10use std::sync::OnceLock;
11
12static ENABLED: OnceLock<bool> = OnceLock::new();
13
14/// Whether networking trace output is enabled (`GRIT_NET_DEBUG` set to something
15/// other than empty / `0` / `false`). Read once and cached.
16pub fn enabled() -> bool {
17    *ENABLED.get_or_init(|| match std::env::var("GRIT_NET_DEBUG") {
18        Ok(v) => !v.is_empty() && v != "0" && v != "false",
19        Err(_) => false,
20    })
21}
22
23/// Emit one `[grit-net] …` trace line to stderr (only when [`enabled`]).
24///
25/// Prefer the [`net_trace!`] macro at call sites so the format arguments are
26/// skipped entirely when tracing is off.
27pub fn line(msg: &str) {
28    eprintln!("[grit-net] {msg}");
29}
30
31/// Emit an env-gated `[grit-net]` trace line. No-op (and no formatting) unless
32/// `GRIT_NET_DEBUG` is set.
33macro_rules! net_trace {
34    ($($arg:tt)*) => {
35        if $crate::net_trace::enabled() {
36            $crate::net_trace::line(&format!($($arg)*));
37        }
38    };
39}
40
41pub(crate) use net_trace;