Skip to main content

respan_gateway/
logging.rs

1//! The gateway's log lines on stderr: a timestamp, a level and a message,
2//! as text or as one JSON object a line.
3
4use std::io::IsTerminal;
5use std::sync::atomic::{AtomicU8, Ordering};
6use std::time::SystemTime;
7
8use clap::ValueEnum;
9use serde::Deserialize;
10use serde_json::{Map, Value, json};
11
12use crate::requests::rfc3339;
13
14/// How log lines are written. `off` silences the request log alone:
15/// warnings are always written.
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, ValueEnum)]
17#[serde(rename_all = "lowercase")]
18pub enum LogFormat {
19    #[default]
20    Text,
21    Json,
22    Off,
23}
24
25/// Color policy for human-readable output. JSON is always unstyled.
26#[derive(Debug, Clone, Copy, Default, ValueEnum)]
27pub enum Color {
28    #[default]
29    Auto,
30    Always,
31    Never,
32}
33
34static COLOR: AtomicU8 = AtomicU8::new(0);
35
36impl Color {
37    pub(crate) fn apply(self) {
38        COLOR.store(self as u8, Ordering::Relaxed);
39    }
40}
41
42fn color_enabled(terminal: bool) -> bool {
43    match COLOR.load(Ordering::Relaxed) {
44        1 => true,
45        2 => false,
46        _ => {
47            terminal
48                && !std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty())
49                && std::env::var_os("TERM").is_none_or(|v| v != "dumb")
50        }
51    }
52}
53
54pub(crate) fn paint(text: &str, style: &str, stderr: bool) -> String {
55    let terminal = if stderr {
56        std::io::stderr().is_terminal()
57    } else {
58        std::io::stdout().is_terminal()
59    };
60    if color_enabled(terminal) {
61        format!("\x1b[{style}m{text}\x1b[0m")
62    } else {
63        text.to_owned()
64    }
65}
66
67/// Style the CLI's aligned reports without changing their text or spacing.
68pub(crate) fn report(text: &str) -> String {
69    if !color_enabled(std::io::stdout().is_terminal()) {
70        return text.to_owned();
71    }
72    let style = |text: &str, code: &str| format!("\x1b[{code}m{text}\x1b[0m");
73    let mut section = "";
74    text.split('\n')
75        .enumerate()
76        .map(|(i, line)| {
77            if i == 0 {
78                return match line.split_once(" listening on ") {
79                    Some((title, address)) => format!(
80                        "{} listening on {}",
81                        style(title, "1;36"),
82                        style(address, "1;32")
83                    ),
84                    None => style(line, "1;36"),
85                };
86            }
87            // Reports use two spaces, a ten-column label, then a space.
88            let Some(prefix) = line
89                .get(..13)
90                .filter(|p| p.starts_with("  ") && p.is_ascii())
91            else {
92                return line.to_owned();
93            };
94            let label = prefix.trim();
95            if !label.is_empty() {
96                section = label;
97            }
98            let value = &line[13..];
99            let value = match section {
100                "auth" => style(value, if value.starts_with("off") { "33" } else { "32" }),
101                "listen" => style(value, "1;32"),
102                "web ui" if value.starts_with("http") => style(value, "4;36"),
103                "web ui" => style(value, if value == "off" { "33" } else { "32" }),
104                "config" | "try" => style(value, "2"),
105                "endpoints" => match value.split_once(' ') {
106                    Some((method, path)) => format!("{} {path}", style(method, "32")),
107                    None => value.to_owned(),
108                },
109                "providers" => match value.split_once("  ") {
110                    Some((name, formats)) => {
111                        format!("{}  {}", style(name, "1"), style(formats, "2"))
112                    }
113                    None => value.to_owned(),
114                },
115                _ => value.to_owned(),
116            };
117            format!("{}{value}", style(prefix, "36"))
118        })
119        .collect::<Vec<_>>()
120        .join("\n")
121}
122
123/// `text` with its control characters escaped, so none can forge a line
124/// or drive a terminal.
125pub(crate) fn escape_controls(text: &str) -> String {
126    text.chars()
127        .flat_map(|c| {
128            if c.is_control() {
129                c.escape_default().collect::<Vec<_>>()
130            } else {
131                vec![c]
132            }
133        })
134        .collect()
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum Level {
139    Info,
140    Warn,
141    Error,
142}
143
144impl Level {
145    fn label(self) -> &'static str {
146        match self {
147            Level::Info => "info",
148            Level::Warn => "warn",
149            Level::Error => "error",
150        }
151    }
152}
153
154impl LogFormat {
155    /// The line for `message` and its `fields`.
156    pub fn line(self, level: Level, message: &str, fields: Map<String, Value>) -> String {
157        let ts = rfc3339(SystemTime::now());
158        match self {
159            LogFormat::Json => {
160                let mut line = fields;
161                line.insert("ts".into(), json!(ts));
162                line.insert("level".into(), json!(level.label()));
163                line.insert("msg".into(), json!(message));
164                Value::Object(line).to_string()
165            }
166            _ => self.tagged(
167                level,
168                &level.label().to_ascii_uppercase(),
169                &escape_controls(message),
170            ),
171        }
172    }
173
174    /// A text line: the time, `tag` (a level, or a request's status) in the
175    /// level's color, and `message`, already escaped and styled.
176    pub fn tagged(self, level: Level, tag: &str, message: &str) -> String {
177        let style = match level {
178            Level::Info => "32",
179            Level::Warn => "33",
180            Level::Error => "31",
181        };
182        let ts = rfc3339(SystemTime::now());
183        let time = ts.split_once('T').map_or(ts.as_str(), |(_, time)| time);
184        format!(
185            "{} {} {message}",
186            paint(time, "2", true),
187            paint(&format!("{tag:<5}"), style, true)
188        )
189    }
190
191    /// Writes a message of the gateway's own to stderr.
192    pub fn say(self, level: Level, message: &str) {
193        eprintln!("{}", self.line(level, message, Map::new()));
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn messages_cannot_inject_terminal_controls_or_json_metadata() {
203        let text = LogFormat::Text.line(Level::Error, "bad\nforged\u{1b}[2J", Map::new());
204        assert!(!text.contains('\n') && !text.contains('\u{1b}'));
205        let fields = json!({"level": "fake", "msg": "fake", "status": 502})
206            .as_object()
207            .expect("fields")
208            .clone();
209        let line = LogFormat::Json.line(Level::Error, "request", fields);
210        let parsed: Value = serde_json::from_str(&line).expect("JSON");
211        assert_eq!(parsed["level"], "error");
212        assert_eq!(parsed["msg"], "request");
213        assert_eq!(parsed["status"], 502);
214    }
215
216    #[test]
217    fn a_line_is_text_or_json() {
218        let text = LogFormat::Text.line(Level::Warn, "careful", Map::new());
219        assert!(text.contains(" WARN  careful"), "{text}");
220        let json = LogFormat::Json.line(Level::Info, "hi", Map::new());
221        let json: Value = serde_json::from_str(&json).unwrap_or_default();
222        assert_eq!(json["level"], "info");
223        assert_eq!(json["msg"], "hi");
224        assert!(json["ts"].as_str().is_some_and(|ts| ts.ends_with('Z')));
225    }
226}