1use std::{fs::OpenOptions, io::{self, Write}};
2
3use chrono::{DateTime, Local};
4
5pub enum TSeverity {
6 DEBUG,
7 INFO,
8 WARN,
9 ERROR,
10}
11
12pub fn log(filename: &'static str, entry: &'static str, severity: Option<TSeverity>, time_format: Option<&'static str>) -> io::Result<String> {
13 let entry_time = formatted_time_entry(time_format);
14
15 let entry_severity = match severity {
16 Some(TSeverity::DEBUG) => "DEBUG ",
17 Some(TSeverity::INFO) => "INFO ",
18 Some(TSeverity::WARN) => "WARN ",
19 Some(TSeverity::ERROR) => "ERROR ",
20 None => "",
21 };
22
23 {
24 let together = format!("{}{} {}\n", entry_severity, entry_time, entry);
25 let entry_bytes = together.as_bytes();
26 record_entry_in_log(filename, &entry_bytes)?;
27 }
28
29 Ok(entry_time)
30}
31
32fn formatted_time_entry(time_format: Option<&'static str>) -> String {
33 let default_time_format = "%Y-%m-%d %H:%M:%S,%3f";
34 let time_format_to_use = time_format.unwrap_or(default_time_format);
35
36 let local: DateTime<Local> = Local::now();
37 let formatted = format!("[{}]", local.format(time_format_to_use).to_string());
38 formatted
39}
40
41fn record_entry_in_log(filename: &str, bytes: &[u8]) -> io::Result<()> {
42 let mut file = OpenOptions::new().
43 append(true).
44 write(true).
45 create(true).
46 open(filename)?;
47 file.write_all(bytes)?;
48 Ok(())
49}