surjection_core/diagnostics/
log.rs1use 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
28pub const LOG_FILE: &str = "surjection.log";
30pub const LOCK_FILE: &str = "surjection.log.lock";
32pub const LOG_ENV_VAR: &str = "SURJECTION_LOG";
34
35const LOCK_WAIT: Duration = Duration::from_millis(500);
38const LOCK_POLL: Duration = Duration::from_millis(5);
39const OPEN_ATTEMPTS: usize = 3;
41const OPEN_RETRY: Duration = Duration::from_millis(20);
42const FLUSH_WAIT: Duration = Duration::from_secs(2);
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct Rotation {
48 pub max_bytes: u64,
51 pub keep: usize,
53}
54
55impl Rotation {
56 pub const DEFAULT: Rotation = Rotation {
58 max_bytes: 1024 * 1024,
59 keep: 2,
60 };
61}
62
63struct Record {
65 time: SystemTime,
66 event: String,
67 fields: Vec<(String, String)>,
68}
69
70enum Message {
71 Line(Record),
72 Rotation(Rotation),
73 Flush(Sender<()>),
75}
76
77pub 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 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 pub fn path(&self) -> PathBuf {
142 self.path.clone()
143 }
144
145 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 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 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
197struct Sink {
199 data: PathBuf,
200 dir: PathBuf,
201 source: &'static str,
202 redactor: Redactor,
203 rotation: Rotation,
204 ready: bool,
206}
207
208impl Sink {
209 fn path(&self) -> PathBuf {
210 self.dir.join(LOG_FILE)
211 }
212
213 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 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 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(¤t);
265 let mut size = std::fs::metadata(long(¤t)).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(¤t);
272 size = 0;
273 }
274 if let Some(file) = file.as_mut() {
275 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 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(¤t));
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(¤t), long(&numbered(1)));
323 }
324}
325
326fn 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
344fn 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
357struct 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
387pub fn install(logger: Logger) {
389 *SINK.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(logger));
390}
391
392pub fn uninstall() {
395 let logger = SINK.write().unwrap_or_else(PoisonError::into_inner).take();
396 if let Some(logger) = logger {
397 logger.flush();
400 }
401}
402
403pub 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
415pub 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
440pub 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
470pub 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
494pub 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}