Skip to main content

zero_client/client/
log.rs

1//! The client's log (`@rocicorp/logger`).
2
3use std::rc::Rc;
4
5/// How much the client logs (`LogLevel`). A level includes the levels after
6/// it: `Warn` logs warnings and errors.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
8pub enum LogLevel {
9    /// Details for debugging.
10    Debug,
11    /// The connection and sync life.
12    Info,
13    /// Something unexpected the client recovered from.
14    Warn,
15    /// Something failed.
16    Error,
17}
18
19impl LogLevel {
20    /// The level as JS names it.
21    pub fn as_str(self) -> &'static str {
22        match self {
23            LogLevel::Debug => "debug",
24            LogLevel::Info => "info",
25            LogLevel::Warn => "warn",
26            LogLevel::Error => "error",
27        }
28    }
29}
30
31/// Where the client's log messages go (`LogSink`).
32pub trait LogSink {
33    /// `context` says which client logged the message, such as `clientID`.
34    fn log(&self, level: LogLevel, message: &str, context: &[(String, String)]);
35}
36
37/// The default sink: standard error.
38pub struct StderrLogSink;
39
40impl LogSink for StderrLogSink {
41    fn log(&self, level: LogLevel, message: &str, context: &[(String, String)]) {
42        let prefix: Vec<String> = context.iter().map(|(k, v)| format!("{k}={v}")).collect();
43        if prefix.is_empty() {
44            eprintln!("{} {message}", level.as_str());
45        } else {
46            eprintln!("{} {} {message}", level.as_str(), prefix.join(" "));
47        }
48    }
49}
50
51/// A sink with a level and a context (`LogContext`): the messages below the
52/// level are dropped without being built.
53#[derive(Clone)]
54pub(crate) struct Log {
55    pub(crate) level: LogLevel,
56    sink: Rc<dyn LogSink>,
57    context: Vec<(String, String)>,
58}
59
60impl Log {
61    pub(crate) fn new(level: LogLevel, sink: Rc<dyn LogSink>) -> Self {
62        Log {
63            level,
64            sink,
65            context: Vec::new(),
66        }
67    }
68
69    pub(crate) fn with(&self, key: &str, value: &str) -> Log {
70        let mut copy = self.clone();
71        copy.context.retain(|(k, _)| k != key);
72        copy.context.push((key.to_owned(), value.to_owned()));
73        copy
74    }
75
76    pub(crate) fn enabled(&self, level: LogLevel) -> bool {
77        level >= self.level
78    }
79
80    pub(crate) fn log(&self, level: LogLevel, message: impl FnOnce() -> String) {
81        if self.enabled(level) {
82            self.sink.log(level, &message(), &self.context);
83        }
84    }
85
86    pub(crate) fn debug(&self, message: impl FnOnce() -> String) {
87        self.log(LogLevel::Debug, message)
88    }
89
90    pub(crate) fn info(&self, message: impl FnOnce() -> String) {
91        self.log(LogLevel::Info, message)
92    }
93
94    pub(crate) fn warn(&self, message: impl FnOnce() -> String) {
95        self.log(LogLevel::Warn, message)
96    }
97
98    pub(crate) fn error(&self, message: impl FnOnce() -> String) {
99        self.log(LogLevel::Error, message)
100    }
101}