Skip to main content

subspace_core/
log.rs

1//! Structured logging for every app built from the Framework: a level, a
2//! target (a board id, `http`, `app`), a message and named fields. Records
3//! go to a rotating JSON Lines file under the state directory and to an
4//! in-memory ring buffer the log viewer reads. Every message and field value
5//! passes through [`redact`] first, so a token or an `Authorization` header
6//! never reaches a file.
7//!
8//! Code builds its handle with [`Logger::new`], a board with its id as the
9//! target. Before [`init`] runs, records
10//! stay in the buffer, so tests never touch the file system.
11
12mod redact;
13mod sink;
14
15use std::path::PathBuf;
16use std::sync::Arc;
17
18use chrono::{DateTime, Utc};
19use serde::{Deserialize, Serialize};
20
21pub use redact::redact;
22pub use sink::{Config, directory, init, level, path, recent, recent_after, set_level};
23
24/// How many records the ring buffer keeps for the viewer.
25pub const BUFFER_RECORDS: usize = 5_000;
26/// The environment variable that overrides the stored level at startup.
27pub const LEVEL_ENV: &str = "SUBSPACE_LOG";
28
29/// How much a record matters, most important first.
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
31#[serde(rename_all = "lowercase")]
32pub enum Level {
33    Error,
34    Warn,
35    Info,
36    Debug,
37    Trace,
38}
39
40/// The levels' names, in [`Level::ALL`] order.
41const NAMES: [&str; 5] = ["error", "warn", "info", "debug", "trace"];
42
43impl Level {
44    pub const ALL: [Self; 5] = [
45        Self::Error,
46        Self::Warn,
47        Self::Info,
48        Self::Debug,
49        Self::Trace,
50    ];
51
52    /// The level's position in [`Level::ALL`].
53    pub fn index(self) -> usize {
54        self as usize
55    }
56
57    pub fn as_str(self) -> &'static str {
58        NAMES[self.index()]
59    }
60
61    /// The level named `text`, in any case; `warning` reads as `warn`.
62    pub fn parse(text: &str) -> Option<Self> {
63        let text = text.trim().to_ascii_lowercase();
64        Self::ALL
65            .into_iter()
66            .find(|level| level.as_str() == text || (text == "warning" && *level == Self::Warn))
67    }
68
69    /// Whether a record at `self` passes a filter set to `threshold`.
70    pub fn passes(self, threshold: Self) -> bool {
71        self <= threshold
72    }
73}
74
75/// One log line.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub struct Record {
78    /// Position in this process's log, from 1.
79    pub seq: u64,
80    pub at: DateTime<Utc>,
81    pub level: Level,
82    pub target: String,
83    pub message: String,
84    #[serde(default, skip_serializing_if = "Vec::is_empty")]
85    pub fields: Vec<(String, String)>,
86}
87
88impl Record {
89    /// `12:34:56.789 WARN  http  GET host /path 429 12ms  status=429`.
90    pub fn line(&self) -> String {
91        let mut line = format!(
92            "{} {:<5} {}  {}",
93            self.at.format("%H:%M:%S%.3f"),
94            self.level.as_str().to_ascii_uppercase(),
95            self.target,
96            self.message
97        );
98        for (key, value) in &self.fields {
99            line.push_str(&format!("  {key}={value}"));
100        }
101        line
102    }
103}
104
105/// A handle that writes records for one target.
106#[derive(Debug, Clone)]
107pub struct Logger {
108    target: Arc<str>,
109}
110
111impl Logger {
112    pub fn new(target: impl Into<String>) -> Self {
113        Self {
114            target: Arc::from(target.into()),
115        }
116    }
117
118    pub fn target(&self) -> &str {
119        &self.target
120    }
121
122    pub fn error(&self, message: impl Into<String>) {
123        self.record(Level::Error, message, &[]);
124    }
125
126    pub fn warn(&self, message: impl Into<String>) {
127        self.record(Level::Warn, message, &[]);
128    }
129
130    pub fn info(&self, message: impl Into<String>) {
131        self.record(Level::Info, message, &[]);
132    }
133
134    pub fn debug(&self, message: impl Into<String>) {
135        self.record(Level::Debug, message, &[]);
136    }
137
138    // qual:api
139    pub fn trace(&self, message: impl Into<String>) {
140        self.record(Level::Trace, message, &[]);
141    }
142
143    /// A record with named fields. Values are redacted like the message.
144    pub fn record(&self, level: Level, message: impl Into<String>, fields: &[(&str, &str)]) {
145        if !level.passes(sink::level()) {
146            return;
147        }
148        let fields = fields
149            .iter()
150            .map(|(key, value)| ((*key).to_owned(), redact(value)))
151            .collect();
152        sink::emit(
153            level,
154            self.target.to_string(),
155            redact(&message.into()),
156            fields,
157        );
158    }
159}
160
161/// `logs` in the app's data directory, beside the state file: the default
162/// log directory.
163pub fn default_directory() -> Option<PathBuf> {
164    crate::state::sibling("logs")
165}
166
167#[cfg(test)]
168mod tests {
169    use chrono::{TimeZone as _, Utc};
170
171    use super::{Level, Logger, Record};
172
173    #[test]
174    fn levels_order_from_error_to_trace_and_parse_their_names() {
175        assert!(Level::Error < Level::Trace);
176        assert!(Level::Warn.passes(Level::Info));
177        assert!(!Level::Debug.passes(Level::Info));
178        assert_eq!(Level::parse(" WARNING "), Some(Level::Warn));
179        assert_eq!(Level::parse("debug"), Some(Level::Debug));
180        assert_eq!(Level::parse("loud"), None);
181        for level in Level::ALL {
182            assert_eq!(Level::parse(level.as_str()), Some(level));
183        }
184    }
185
186    #[test]
187    fn a_record_line_carries_the_time_level_target_message_and_fields() {
188        let record = Record {
189            seq: 1,
190            at: Utc.with_ymd_and_hms(2026, 10, 18, 7, 8, 9).unwrap(),
191            level: Level::Warn,
192            target: "http".into(),
193            message: "GET host /path".into(),
194            fields: vec![("status".into(), "429".into())],
195        };
196        assert_eq!(
197            record.line(),
198            "07:08:09.000 WARN  http  GET host /path  status=429"
199        );
200        let json = serde_json::to_string(&record).unwrap();
201        assert!(json.contains("\"level\":\"warn\""), "{json}");
202        assert_eq!(serde_json::from_str::<Record>(&json).unwrap(), record);
203    }
204
205    #[test]
206    fn a_logger_records_its_target_and_redacts_what_it_records() {
207        let logger = Logger::new("github.cache");
208        assert_eq!(logger.target(), "github.cache");
209        logger.record(
210            Level::Error,
211            // Fake credentials, split so secret scanners do not flag the source.
212            concat!("Authorization: Bear", "er abc.def.ghi failed"),
213            &[(
214                "jwt",
215                concat!(
216                    "eyJhbGciOiJSUzI1NiIs",
217                    ".eyJzdWIiOiIxMjM0NTY3ODkwIn0",
218                    ".c2lnbmF0dXJl"
219                ),
220            )],
221        );
222        let last = super::recent()
223            .into_iter()
224            .rev()
225            .find(|record| record.target == "github.cache")
226            .unwrap();
227        assert!(!last.message.contains("abc.def.ghi"), "{}", last.message);
228        assert!(!last.fields[0].1.contains("eyJ"), "{}", last.fields[0].1);
229    }
230}