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/// `<state dir>/subspace/logs`, the default log directory.
162pub fn default_directory() -> Option<PathBuf> {
163    crate::state::sibling("logs")
164}
165
166#[cfg(test)]
167mod tests {
168    use chrono::{TimeZone as _, Utc};
169
170    use super::{Level, Logger, Record};
171
172    #[test]
173    fn levels_order_from_error_to_trace_and_parse_their_names() {
174        assert!(Level::Error < Level::Trace);
175        assert!(Level::Warn.passes(Level::Info));
176        assert!(!Level::Debug.passes(Level::Info));
177        assert_eq!(Level::parse(" WARNING "), Some(Level::Warn));
178        assert_eq!(Level::parse("debug"), Some(Level::Debug));
179        assert_eq!(Level::parse("loud"), None);
180        for level in Level::ALL {
181            assert_eq!(Level::parse(level.as_str()), Some(level));
182        }
183    }
184
185    #[test]
186    fn a_record_line_carries_the_time_level_target_message_and_fields() {
187        let record = Record {
188            seq: 1,
189            at: Utc.with_ymd_and_hms(2026, 10, 18, 7, 8, 9).unwrap(),
190            level: Level::Warn,
191            target: "http".into(),
192            message: "GET host /path".into(),
193            fields: vec![("status".into(), "429".into())],
194        };
195        assert_eq!(
196            record.line(),
197            "07:08:09.000 WARN  http  GET host /path  status=429"
198        );
199        let json = serde_json::to_string(&record).unwrap();
200        assert!(json.contains("\"level\":\"warn\""), "{json}");
201        assert_eq!(serde_json::from_str::<Record>(&json).unwrap(), record);
202    }
203
204    #[test]
205    fn a_logger_records_its_target_and_redacts_what_it_records() {
206        let logger = Logger::new("github.cache");
207        assert_eq!(logger.target(), "github.cache");
208        logger.record(
209            Level::Error,
210            // Fake credentials, split so secret scanners do not flag the source.
211            concat!("Authorization: Bear", "er abc.def.ghi failed"),
212            &[(
213                "jwt",
214                concat!(
215                    "eyJhbGciOiJSUzI1NiIs",
216                    ".eyJzdWIiOiIxMjM0NTY3ODkwIn0",
217                    ".c2lnbmF0dXJl"
218                ),
219            )],
220        );
221        let last = super::recent()
222            .into_iter()
223            .rev()
224            .find(|record| record.target == "github.cache")
225            .unwrap();
226        assert!(!last.message.contains("abc.def.ghi"), "{}", last.message);
227        assert!(!last.fields[0].1.contains("eyJ"), "{}", last.fields[0].1);
228    }
229}