Skip to main content

ferroui_splat/logging/
debug_logger.rs

1//! `DebugLogger`.
2
3use super::{short_type_name, ILogger, LogLevel};
4use std::cell::Cell;
5use std::error::Error;
6
7/// A logger that writes to the debug output (`DebugLogger`), the messages of its level and above.
8///
9/// A message with a type is written with the name of the type as its category, as
10/// `Debug.WriteLine(message, category)` writes it: `Category: message`.
11// Deviation (DEVIATIONS.md, Splat): the debug output of .NET (`System.Diagnostics.Debug`) is the
12// standard error here, in every build.
13#[derive(Default)]
14pub struct DebugLogger {
15    level: Cell<LogLevel>,
16}
17
18impl DebugLogger {
19    /// A logger at the level `Debug`.
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    /// Sets the level (`Level { set; }`).
25    pub fn set_level(&self, level: LogLevel) {
26        self.level.set(level);
27    }
28
29    fn write_line(message: &str, category: Option<&str>) {
30        match category {
31            Some(category) => eprintln!("{category}: {message}"),
32            None => eprintln!("{message}"),
33        }
34    }
35}
36
37impl ILogger for DebugLogger {
38    fn level(&self) -> LogLevel {
39        self.level.get()
40    }
41
42    fn write(&self, message: &str, log_level: LogLevel) {
43        if log_level < self.level.get() {
44            return;
45        }
46        Self::write_line(message, None);
47    }
48
49    fn write_exception(&self, exception: &dyn Error, message: &str, log_level: LogLevel) {
50        if log_level < self.level.get() {
51            return;
52        }
53        Self::write_line(&format!("{message} - {exception}"), None);
54    }
55
56    fn write_with_type(&self, message: &str, type_name: &'static str, log_level: LogLevel) {
57        if log_level < self.level.get() {
58            return;
59        }
60        Self::write_line(message, Some(short_type_name(type_name)));
61    }
62
63    fn write_exception_with_type(
64        &self,
65        exception: &dyn Error,
66        message: &str,
67        type_name: &'static str,
68        log_level: LogLevel,
69    ) {
70        if log_level < self.level.get() {
71            return;
72        }
73        Self::write_line(&format!("{message} - {exception}"), Some(short_type_name(type_name)));
74    }
75}