1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#[cfg(feature = "display")]
use std::fmt::Write;
use chrono::{DateTime, Utc};
#[cfg(feature = "display")]
use crossterm::style::{StyledContent, Stylize};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::deployment::State;
pub const STATE_MESSAGE: &str = "NEW STATE";
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Item {
pub id: Uuid,
pub timestamp: DateTime<Utc>,
pub state: State,
pub level: Level,
pub file: Option<String>,
pub line: Option<u32>,
pub target: String,
pub fields: Vec<u8>,
}
#[cfg(feature = "display")]
impl std::fmt::Display for Item {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let datetime: chrono::DateTime<chrono::Local> = DateTime::from(self.timestamp);
let message = match serde_json::from_slice(&self.fields).unwrap() {
serde_json::Value::String(str_value) if str_value == STATE_MESSAGE => {
writeln!(f)?;
format!("Entering {} state", self.state)
.bold()
.blue()
.to_string()
}
serde_json::Value::Object(map) => {
let mut simple = None;
let mut extra = vec![];
for (key, value) in map.iter() {
match key.as_str() {
"message" => simple = value.as_str(),
_ => extra.push(format!("{key}={value}")),
}
}
let mut output = if extra.is_empty() {
String::new()
} else {
format!("{{{}}} ", extra.join(" "))
};
if !self.target.is_empty() {
let target = format!("{}:", self.target).dim();
write!(output, "{target} ")?;
}
if let Some(msg) = simple {
write!(output, "{msg}")?;
}
output
}
other => other.to_string(),
};
write!(
f,
"{} {} {}",
datetime.format("%Y-%m-%dT%H:%M:%S.%fZ").to_string().dim(),
self.level.get_colored(),
message
)
}
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Level {
Trace,
Debug,
Info,
Warn,
Error,
}
#[cfg(feature = "display")]
impl Level {
fn get_colored(&self) -> StyledContent<&str> {
match self {
Level::Trace => "TRACE".magenta(),
Level::Debug => "DEBUG".blue(),
Level::Info => " INFO".green(),
Level::Warn => " WARN".yellow(),
Level::Error => "ERROR".red(),
}
}
}
impl From<&tracing::Level> for Level {
fn from(level: &tracing::Level) -> Self {
match *level {
tracing::Level::ERROR => Self::Error,
tracing::Level::WARN => Self::Warn,
tracing::Level::INFO => Self::Info,
tracing::Level::DEBUG => Self::Debug,
tracing::Level::TRACE => Self::Trace,
}
}
}