statime_linux/
tracing.rs

1use std::str::FromStr;
2
3use serde::Deserialize;
4use tracing::metadata::LevelFilter;
5
6#[derive(Debug, Default, Copy, Clone, Deserialize, PartialEq, Eq)]
7#[serde(rename_all = "lowercase")]
8pub enum LogLevel {
9    /// The "trace" level.
10    ///
11    /// Designates very low priority, often extremely verbose, information.
12    Trace = 0,
13    /// The "debug" level.
14    ///
15    /// Designates lower priority information.
16    Debug = 1,
17    /// The "info" level.
18    ///
19    /// Designates useful information.
20    #[default]
21    Info = 2,
22    /// The "warn" level.
23    ///
24    /// Designates hazardous situations.
25    Warn = 3,
26    /// The "error" level.
27    ///
28    /// Designates very serious errors.
29    Error = 4,
30}
31
32pub struct UnknownLogLevel;
33
34impl FromStr for LogLevel {
35    type Err = UnknownLogLevel;
36
37    fn from_str(s: &str) -> Result<Self, Self::Err> {
38        match s {
39            "trace" => Ok(LogLevel::Trace),
40            "debug" => Ok(LogLevel::Debug),
41            "info" => Ok(LogLevel::Info),
42            "warn" => Ok(LogLevel::Warn),
43            "error" => Ok(LogLevel::Error),
44            _ => Err(UnknownLogLevel),
45        }
46    }
47}
48
49impl From<LogLevel> for tracing::Level {
50    fn from(value: LogLevel) -> Self {
51        match value {
52            LogLevel::Trace => tracing::Level::TRACE,
53            LogLevel::Debug => tracing::Level::DEBUG,
54            LogLevel::Info => tracing::Level::INFO,
55            LogLevel::Warn => tracing::Level::WARN,
56            LogLevel::Error => tracing::Level::ERROR,
57        }
58    }
59}
60
61impl From<LogLevel> for LevelFilter {
62    fn from(value: LogLevel) -> Self {
63        LevelFilter::from_level(value.into())
64    }
65}
66
67pub fn tracing_init(level: impl Into<LevelFilter>) -> tracing_subscriber::fmt::Subscriber {
68    tracing_subscriber::fmt().with_max_level(level).finish()
69}