vault_core/telemetry.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Structured logging, shared by all three binaries.
4//!
5//! Before this module the workspace had no `tracing`, no metrics crate and no
6//! structured log anywhere: a failure in production left `println!` output and
7//! nothing correlatable. Everything in the operability goals — uptime
8//! monitoring, failure detection, API analytics — depends on this existing
9//! first, which is why it landed ahead of the rest of its phase.
10//!
11//! # Three rules, and they are not style preferences
12//!
13//! 1. **Logs go to stderr, always.** The CLI's stdout is a machine-readable
14//! contract (`{"ok":true,…}`); a log line written there corrupts the JSON
15//! envelope an agent is parsing. `with_writer(std::io::stderr)` is what makes
16//! `unv … --json | jq` keep working with `UNV_LOG=debug` set.
17//! 2. **Never log a secret value.** Log the fingerprint (`out::fingerprint`),
18//! the entry id, or the provider name — never `api_key`, never a password,
19//! never a session token. A log file is not encrypted and is routinely
20//! shipped somewhere else.
21//! 3. **Logging is off unless asked for.** The default level is chosen by each
22//! binary, and every one of them is quiet enough that normal operation
23//! produces nothing on stderr. A secrets manager that chatters is a secrets
24//! manager whose output nobody reads.
25//!
26//! # Configuring it
27//!
28//! | Variable | Effect |
29//! | -------- | ------ |
30//! | `UNV_LOG` | `tracing` filter directive (`info`, `unv_server=debug`, …). Checked first. |
31//! | `RUST_LOG` | Same, checked only when `UNV_LOG` is unset, so an unrelated `RUST_LOG` in the environment still works. |
32//! | `UNV_LOG_FORMAT` | `json` for one JSON object per line; anything else is the human format. |
33//!
34//! An unparseable filter falls back to the caller's default rather than
35//! panicking: a typo in an environment variable must not stop a server booting.
36
37use std::sync::OnceLock;
38
39/// Set once by the first successful [`init`], so a second call is a no-op
40/// rather than a panic from `tracing`'s global-subscriber guard. The desktop
41/// app can host `unv-server`'s router in-process, which is exactly the case
42/// where two `init` calls happen in one program.
43static INITIALISED: OnceLock<()> = OnceLock::new();
44
45/// Installs the process-wide subscriber. Safe to call more than once; only the
46/// first call has any effect.
47///
48/// `service` names the binary and is attached to the startup line so a merged
49/// log tells `unv-server` apart from a desktop app hosting the same router.
50/// `default_level` applies when neither `UNV_LOG` nor `RUST_LOG` is set.
51pub fn init(service: &str, default_level: &str) {
52 if INITIALISED.set(()).is_err() {
53 return;
54 }
55
56 let directive = std::env::var("UNV_LOG")
57 .or_else(|_| std::env::var("RUST_LOG"))
58 .unwrap_or_else(|_| default_level.to_string());
59
60 let filter = tracing_subscriber::EnvFilter::try_new(&directive)
61 .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(default_level));
62
63 let json = std::env::var("UNV_LOG_FORMAT")
64 .map(|v| v.eq_ignore_ascii_case("json"))
65 .unwrap_or(false);
66
67 // `try_init` rather than `init`: another crate in the process may already
68 // own the global subscriber, and losing that race is not an error worth
69 // aborting a boot over.
70 if json {
71 let _ = tracing_subscriber::fmt()
72 .with_env_filter(filter)
73 .with_writer(std::io::stderr)
74 .json()
75 .try_init();
76 } else {
77 let _ = tracing_subscriber::fmt()
78 .with_env_filter(filter)
79 .with_writer(std::io::stderr)
80 .try_init();
81 }
82
83 tracing::debug!(
84 service,
85 version = env!("CARGO_PKG_VERSION"),
86 filter = %directive,
87 "logging initialised"
88 );
89}
90
91/// True once [`init`] has run in this process. Tests use it; nothing else
92/// should need to ask.
93pub fn is_initialised() -> bool {
94 INITIALISED.get().is_some()
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn init_is_idempotent() {
103 init("test", "error");
104 assert!(is_initialised());
105 // A second call must not panic on tracing's global-subscriber guard.
106 init("test", "error");
107 assert!(is_initialised());
108 }
109}