use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Level {
Trace = 5,
Debug = 10,
Info = 20,
Success = 25,
Warning = 30,
Error = 40,
Fail = 45,
Critical = 50,
}
impl PartialOrd for Level {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Level {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
(*self as u8).cmp(&(*other as u8))
}
}
impl Level {
pub fn as_str(&self) -> &'static str {
match self {
Level::Trace => "TRACE",
Level::Debug => "DEBUG",
Level::Info => "INFO",
Level::Success => "SUCCESS",
Level::Warning => "WARNING",
Level::Error => "ERROR",
Level::Fail => "FAIL",
Level::Critical => "CRITICAL",
}
}
pub fn priority(&self) -> u8 {
*self as u8
}
pub fn default_color(&self) -> &'static str {
match self {
Level::Trace => "36", Level::Debug => "34", Level::Info => "37", Level::Success => "32", Level::Warning => "33", Level::Error => "31", Level::Fail => "35", Level::Critical => "91", }
}
pub fn all_levels() -> Vec<Level> {
vec![
Level::Trace,
Level::Debug,
Level::Info,
Level::Success,
Level::Warning,
Level::Error,
Level::Fail,
Level::Critical,
]
}
pub fn from_priority(priority: u8) -> Option<Self> {
match priority {
5 => Some(Level::Trace),
10 => Some(Level::Debug),
20 => Some(Level::Info),
25 => Some(Level::Success),
30 => Some(Level::Warning),
40 => Some(Level::Error),
45 => Some(Level::Fail),
50 => Some(Level::Critical),
_ => None,
}
}
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl FromStr for Level {
type Err = crate::error::LoglyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_uppercase().as_str() {
"TRACE" => Ok(Level::Trace),
"DEBUG" => Ok(Level::Debug),
"INFO" => Ok(Level::Info),
"SUCCESS" => Ok(Level::Success),
"WARNING" | "WARN" => Ok(Level::Warning),
"ERROR" => Ok(Level::Error),
"FAIL" => Ok(Level::Fail),
"CRITICAL" | "CRIT" => Ok(Level::Critical),
_ => Err(crate::error::LoglyError::InvalidLevel(s.to_string())),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CustomLevel {
pub name: String,
pub priority: u8,
pub color: String,
}
impl CustomLevel {
pub fn new(name: String, priority: u8, color: String) -> Self {
Self {
name,
priority,
color,
}
}
}