Skip to main content

surjection_core/diagnostics/
log.rs

1//! `<SURJECTION_HOME>/logs/surjection.log` (SPEC 4.5): one redacted line per
2//! event, size-capped and rotated. Local only, never uploaded.
3//!
4//! Callers log event names and chosen fields only: never messages, secret
5//! or environment values, headers, file contents or search words. Each
6//! field value still goes through the [`Redactor`] before it is written.
7//!
8//! The CLI and the app [`install`] one [`Logger`] per process and
9//! [`uninstall`] it before they exit; with none installed (core tests,
10//! library callers) [`event`] does nothing.
11
12use std::fmt::{self, Display, Write as _};
13use std::fs::{File, OpenOptions, TryLockError};
14use std::io::Write as _;
15use std::path::{Path, PathBuf};
16use std::sync::mpsc::{self, Receiver, Sender};
17use std::sync::{Arc, Mutex, PoisonError, RwLock};
18use std::thread::{self, JoinHandle};
19use std::time::{Duration, Instant, SystemTime};
20
21use super::redact::Redactor;
22use crate::env::Env;
23use crate::error::{CoreError, ErrorCode};
24use crate::fs::long;
25use crate::paths::SurjectionHome;
26use crate::store::utc_datetime;
27
28/// The log file inside `logs/`.
29pub const LOG_FILE: &str = "surjection.log";
30/// The lock writers hold while appending and rotating.
31pub const LOCK_FILE: &str = "surjection.log.lock";
32/// Set to `off` (or `0`, `false`, `no`) to turn the log off.
33pub const LOG_ENV_VAR: &str = "SURJECTION_LOG";
34
35/// How long the writer waits for the lock before appending without
36/// rotating.
37const LOCK_WAIT: Duration = Duration::from_millis(500);
38const LOCK_POLL: Duration = Duration::from_millis(5);
39/// Attempts to open the log file (another process may be renaming it).
40const OPEN_ATTEMPTS: usize = 3;
41const OPEN_RETRY: Duration = Duration::from_millis(20);
42/// How long [`Logger::flush`] waits for the writer.
43const FLUSH_WAIT: Duration = Duration::from_secs(2);
44
45/// When the log rotates and how many older files stay.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct Rotation {
48    /// The current file never grows past this (a single longer line
49    /// still gets its own file).
50    pub max_bytes: u64,
51    /// Older files kept: `surjection.log.1` (newest) to `surjection.log.<keep>`.
52    pub keep: usize,
53}
54
55impl Rotation {
56    /// 1 MiB, two older files.
57    pub const DEFAULT: Rotation = Rotation {
58        max_bytes: 1024 * 1024,
59        keep: 2,
60    };
61}
62
63/// One event as the caller gave it; rendered and redacted by the writer.
64struct Record {
65    time: SystemTime,
66    event: String,
67    fields: Vec<(String, String)>,
68}
69
70enum Message {
71    Line(Record),
72    Rotation(Rotation),
73    /// Answered once everything sent before it is written.
74    Flush(Sender<()>),
75}
76
77/// Writes redacted lines to one data folder's log. The caller only queues
78/// the event; one background thread renders, redacts and writes (file
79/// I/O, the lock, rotation and retries never run on the caller's thread).
80/// Dropping the logger writes what is queued before it returns.
81pub struct Logger {
82    path: PathBuf,
83    env: Env,
84    sender: Mutex<Option<Sender<Message>>>,
85    writer: Mutex<Option<JoinHandle<()>>>,
86}
87
88impl fmt::Debug for Logger {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.debug_struct("Logger")
91            .field("path", &self.path)
92            .finish_non_exhaustive()
93    }
94}
95
96impl Logger {
97    /// The log of `home`, written as `source` (`cli`, `app`); `None` when
98    /// [`LOG_ENV_VAR`] turns it off (or the writer thread cannot start).
99    pub fn for_home(env: &Env, home: &SurjectionHome, source: &'static str) -> Option<Logger> {
100        let off = env
101            .var(LOG_ENV_VAR)
102            .or_else(|| env.var(crate::brand::legacy::LOG_ENV_VAR))
103            .and_then(|value| value.to_str())
104            .is_some_and(|value| {
105                matches!(
106                    value.trim().to_ascii_lowercase().as_str(),
107                    "off" | "0" | "false" | "no"
108                )
109            });
110        if off {
111            return None;
112        }
113        let sink = Sink {
114            data: home.path.clone(),
115            dir: home.logs_dir(),
116            source,
117            redactor: Redactor::new(env, &home.path),
118            rotation: Rotation::DEFAULT,
119            ready: false,
120        };
121        let path = sink.path();
122        let (sender, receiver) = mpsc::channel();
123        let writer = thread::Builder::new()
124            .name("surjection-log".to_owned())
125            .spawn(move || sink.run(receiver))
126            .ok()?;
127        Some(Logger {
128            path,
129            env: env.clone(),
130            sender: Mutex::new(Some(sender)),
131            writer: Mutex::new(Some(writer)),
132        })
133    }
134
135    pub fn with_rotation(self, rotation: Rotation) -> Self {
136        self.send(Message::Rotation(rotation));
137        self
138    }
139
140    /// The current log file.
141    pub fn path(&self) -> PathBuf {
142        self.path.clone()
143    }
144
145    /// Queues one line. Nothing is written while the data folder does not
146    /// exist (a log never creates it); I/O errors are ignored.
147    pub fn write(&self, event: &str, fields: &[(&str, &dyn Display)]) {
148        self.send(Message::Line(Record {
149            time: self.env.now(),
150            event: clean(event),
151            fields: fields
152                .iter()
153                .map(|(key, value)| (clean(key), value.to_string()))
154                .collect(),
155        }));
156    }
157
158    /// Waits (up to two seconds) until every line queued so far is written.
159    pub fn flush(&self) {
160        let (ack, done) = mpsc::channel();
161        self.send(Message::Flush(ack));
162        let _ = done.recv_timeout(FLUSH_WAIT);
163    }
164
165    fn send(&self, message: Message) {
166        if let Some(sender) = self
167            .sender
168            .lock()
169            .unwrap_or_else(PoisonError::into_inner)
170            .as_ref()
171        {
172            let _ = sender.send(message);
173        }
174    }
175}
176
177impl Drop for Logger {
178    fn drop(&mut self) {
179        // Closing the channel ends the writer once it has written the rest.
180        drop(
181            self.sender
182                .lock()
183                .unwrap_or_else(PoisonError::into_inner)
184                .take(),
185        );
186        if let Some(writer) = self
187            .writer
188            .lock()
189            .unwrap_or_else(PoisonError::into_inner)
190            .take()
191        {
192            let _ = writer.join();
193        }
194    }
195}
196
197/// The writer thread's side: where and how lines are written.
198struct Sink {
199    data: PathBuf,
200    dir: PathBuf,
201    source: &'static str,
202    redactor: Redactor,
203    rotation: Rotation,
204    /// `logs/` exists: checked until it does, then never again.
205    ready: bool,
206}
207
208impl Sink {
209    fn path(&self) -> PathBuf {
210        self.dir.join(LOG_FILE)
211    }
212
213    /// Writes whatever has arrived, in batches, until the channel closes.
214    fn run(mut self, receiver: Receiver<Message>) {
215        while let Ok(first) = receiver.recv() {
216            let mut lines = Vec::new();
217            let mut acks = Vec::new();
218            for message in std::iter::once(first).chain(receiver.try_iter()) {
219                match message {
220                    Message::Line(record) => lines.push(self.render(&record)),
221                    Message::Rotation(rotation) => self.rotation = rotation,
222                    Message::Flush(ack) => acks.push(ack),
223                }
224            }
225            self.write(&lines);
226            for ack in acks {
227                let _ = ack.send(());
228            }
229        }
230    }
231
232    fn render(&self, record: &Record) -> String {
233        let mut line = format!(
234            "{} {} pid={} {}",
235            utc_datetime(record.time),
236            self.source,
237            std::process::id(),
238            record.event
239        );
240        // Each value is redacted before it is quoted, so a value with
241        // quotes or backslashes is still matched as it was resolved.
242        for (key, value) in &record.fields {
243            let value = self.redactor.redact(value);
244            let _ = write!(line, " {key}={}", Quoted(&value));
245        }
246        line.push('\n');
247        line
248    }
249
250    /// Appends `lines` under the lock, one write call per line, rotating
251    /// before a line that would push the file past the cap.
252    fn write(&mut self, lines: &[String]) {
253        if lines.is_empty() {
254            return;
255        }
256        if !self.ready {
257            if !long(&self.data).is_dir() || std::fs::create_dir_all(long(&self.dir)).is_err() {
258                return;
259            }
260            self.ready = true;
261        }
262        let lock = self.lock();
263        let current = self.path();
264        let mut file = open_append(&current);
265        let mut size = std::fs::metadata(long(&current)).map_or(0, |meta| meta.len());
266        for line in lines {
267            let incoming = line.len() as u64;
268            if lock.is_some() && size > 0 && size + incoming > self.rotation.max_bytes {
269                drop(file.take());
270                self.rotate();
271                file = open_append(&current);
272                size = 0;
273            }
274            if let Some(file) = file.as_mut() {
275                // A whole line per write call, even from a writer that
276                // could not get the lock.
277                if file.write_all(line.as_bytes()).is_ok() {
278                    size += incoming;
279                }
280            }
281        }
282        drop(file);
283        if let Some(lock) = lock {
284            let _ = lock.unlock();
285        }
286    }
287
288    fn lock(&self) -> Option<File> {
289        let file = OpenOptions::new()
290            .read(true)
291            .write(true)
292            .create(true)
293            .truncate(false)
294            .open(long(&self.dir.join(LOCK_FILE)))
295            .ok()?;
296        let deadline = Instant::now() + LOCK_WAIT;
297        loop {
298            match file.try_lock() {
299                Ok(()) => return Some(file),
300                Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
301                    thread::sleep(LOCK_POLL);
302                }
303                Err(_) => return None,
304            }
305        }
306    }
307
308    /// `.N-1 -> .N ... .1 -> .2`, current `-> .1`. Runs under the lock.
309    fn rotate(&self) {
310        let current = self.path();
311        let numbered = |n: usize| self.dir.join(format!("{LOG_FILE}.{n}"));
312        if self.rotation.keep == 0 {
313            let _ = std::fs::remove_file(long(&current));
314            return;
315        }
316        for n in (1..self.rotation.keep).rev() {
317            let from = numbered(n);
318            if long(&from).exists() {
319                let _ = std::fs::rename(long(&from), long(&numbered(n + 1)));
320            }
321        }
322        let _ = std::fs::rename(long(&current), long(&numbered(1)));
323    }
324}
325
326/// The log file opened for appending, retried briefly (another process
327/// may hold it while it rotates).
328fn open_append(path: &Path) -> Option<File> {
329    for attempt in 0..OPEN_ATTEMPTS {
330        if let Ok(file) = OpenOptions::new()
331            .create(true)
332            .append(true)
333            .open(long(path))
334        {
335            return Some(file);
336        }
337        if attempt + 1 < OPEN_ATTEMPTS {
338            thread::sleep(OPEN_RETRY);
339        }
340    }
341    None
342}
343
344/// Event and key names: printable ASCII without spaces or `=`.
345fn clean(name: &str) -> String {
346    name.chars()
347        .map(|c| {
348            if c.is_ascii_graphic() && c != '=' {
349                c
350            } else {
351                '_'
352            }
353        })
354        .collect()
355}
356
357/// A field value: bare when it is one plain word, else quoted with `"`,
358/// `\` and control characters escaped.
359struct Quoted<'a>(&'a str);
360
361impl Display for Quoted<'_> {
362    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363        let plain = !self.0.is_empty()
364            && self
365                .0
366                .chars()
367                .all(|c| c.is_ascii_graphic() && !matches!(c, '"' | '\\' | '='));
368        if plain {
369            return f.write_str(self.0);
370        }
371        f.write_char('"')?;
372        for c in self.0.chars() {
373            match c {
374                '"' => f.write_str("\\\"")?,
375                '\\' => f.write_str("\\\\")?,
376                '\n' => f.write_str("\\n")?,
377                c if c.is_control() => f.write_char(' ')?,
378                c => f.write_char(c)?,
379            }
380        }
381        f.write_char('"')
382    }
383}
384
385static SINK: RwLock<Option<Arc<Logger>>> = RwLock::new(None);
386
387/// Makes `logger` the process's log.
388pub fn install(logger: Logger) {
389    *SINK.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(logger));
390}
391
392/// Stops logging in this process after writing every queued line (call it
393/// before the process exits).
394pub fn uninstall() {
395    let logger = SINK.write().unwrap_or_else(PoisonError::into_inner).take();
396    if let Some(logger) = logger {
397        // Another thread may still hold the logger for a moment: flush so
398        // the lines are written even when this is not the last reference.
399        logger.flush();
400    }
401}
402
403/// Logs one event to the installed logger, if any.
404pub fn event(name: &str, fields: &[(&str, &dyn Display)]) {
405    let logger = SINK
406        .read()
407        .unwrap_or_else(PoisonError::into_inner)
408        .as_ref()
409        .map(Arc::clone);
410    if let Some(logger) = logger {
411        logger.write(name, fields);
412    }
413}
414
415/// Logs the end of a command or IPC call `name`: `outcome=ok`, or
416/// `outcome=error code=<code>`, and how long it took.
417pub fn finished(event_name: &str, name: &str, error: Option<ErrorCode>, started: Instant) {
418    let duration = started.elapsed().as_millis();
419    match error {
420        None => event(
421            event_name,
422            &[
423                ("name", &name),
424                ("outcome", &"ok"),
425                ("duration_ms", &duration),
426            ],
427        ),
428        Some(code) => event(
429            event_name,
430            &[
431                ("name", &name),
432                ("outcome", &"error"),
433                ("code", &code.as_str()),
434                ("duration_ms", &duration),
435            ],
436        ),
437    }
438}
439
440/// Logs a network request: the host only (never the path or query), the
441/// HTTP status or the error code, and how long it took.
442pub fn http(kind: &str, url: &str, result: Result<u16, &CoreError>, started: Instant) {
443    let host = url::Url::parse(url)
444        .ok()
445        .and_then(|url| url.host_str().map(str::to_owned))
446        .unwrap_or_else(|| "unknown".to_owned());
447    let duration = started.elapsed().as_millis();
448    match result {
449        Ok(status) => event(
450            "http",
451            &[
452                ("kind", &kind),
453                ("host", &host),
454                ("status", &status),
455                ("duration_ms", &duration),
456            ],
457        ),
458        Err(err) => event(
459            "http",
460            &[
461                ("kind", &kind),
462                ("host", &host),
463                ("code", &err.code().as_str()),
464                ("duration_ms", &duration),
465            ],
466        ),
467    }
468}
469
470/// The last `n` lines of the log of `home` (the newest older file fills
471/// in when the current one is short). Lines were redacted when written.
472pub fn tail(home: &SurjectionHome, n: usize) -> Vec<String> {
473    let dir = home.logs_dir();
474    let read = |path: &Path| std::fs::read(long(path)).ok();
475    let lines_of = |bytes: Vec<u8>| -> Vec<String> {
476        String::from_utf8_lossy(&bytes)
477            .lines()
478            .filter(|line| !line.trim().is_empty())
479            .map(str::to_owned)
480            .collect()
481    };
482    let mut lines = read(&dir.join(LOG_FILE)).map(lines_of).unwrap_or_default();
483    if lines.len() < n
484        && let Some(older) = read(&dir.join(format!("{LOG_FILE}.1"))).map(lines_of)
485    {
486        let mut all = older;
487        all.extend(lines);
488        lines = all;
489    }
490    let skip = lines.len().saturating_sub(n);
491    lines.split_off(skip)
492}
493
494/// The `code=` values of `lines`, newest first, with how often each
495/// appears.
496pub fn error_codes(lines: &[String]) -> Vec<(String, usize)> {
497    let mut codes: Vec<(String, usize)> = Vec::new();
498    for line in lines.iter().rev() {
499        let Some(code) = line
500            .split_whitespace()
501            .find_map(|word| word.strip_prefix("code="))
502            .filter(|code| !code.is_empty())
503        else {
504            continue;
505        };
506        match codes.iter_mut().find(|(known, _)| known == code) {
507            Some((_, count)) => *count += 1,
508            None => codes.push((code.to_owned(), 1)),
509        }
510    }
511    codes
512}