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
#![crate_type = "lib"]
use std::{
io::Write,
net::{TcpStream, Ipv4Addr},
time::{SystemTime, UNIX_EPOCH},
error::Error, fmt::{self, Display},
};
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};
use serde_json::json;
struct Connection {
ip: &'static str, port: u16,
}
impl Connection {
fn default(&self) -> Self {
Connection { ip: "255.255.255.255", port: 3306 }
}
}
struct Logger {
id: u32,
connection: Option<Connection>,
}
impl Logger {
}
#[derive(Serialize, Deserialize)]
struct LogMessage {
timestamp: DateTime<Utc>,
level: Level,
message: String,
}
#[derive(Serialize, Deserialize, Clone)]
enum Level {
INFO,
WARNING,
ERROR,
DEBUG,
Custom(String),
}
impl Display for Level {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Level::INFO => write!(f, "INFO"),
Level::WARNING => write!(f, "WARNING"),
Level::ERROR => write!(f, "ERROR"),
Level::DEBUG => write!(f, "DEBUG"),
Level::Custom(str) => write!(f, "{}", str),
}
}
}
fn send_log_message(log_message: &LogMessage) -> Result<(), Box<dyn Error>> {
let mut stream = TcpStream::connect("graylog.example.com:12201")?;
let json_string = serde_json::to_string(log_message)?;
stream.write_all(json_string.as_bytes())?;
Ok(())
}
fn log(message: &str, level: Level) -> Result<(), Box<dyn Error>> {
let log_message = LogMessage {
message: message.to_string(),
timestamp: Utc::now(),
level,
};
send_log_message(&log_message)
}
#[test]
fn test_levels() {
assert_eq!("INFO", Level::INFO.to_string());
assert_eq!("WARNING", Level::WARNING.to_string());
assert_eq!("ERROR", Level::ERROR.to_string());
assert_eq!("DEBUG", Level::DEBUG.to_string());
}