qust_ds/
log.rs

1use std::{
2    fs,
3    fs::File,
4    path::Path,
5    collections::HashMap,
6    sync::Mutex, 
7    io::Write,
8};
9use chrono::Local;
10
11pub type HmLog = HashMap<String, Mutex<File>>;
12pub struct MyLog<T> {
13    pub path: String,
14    pub io: T,
15}
16
17impl<T> MyLog<T> {
18    pub fn from_file(path: &str) -> MyLog<File> {
19        let file = File::create(path.to_string() + ".log").unwrap();
20        MyLog { path: path.to_string(), io: file }
21    }
22
23   pub fn from_dir(path_str: &str) -> MyLog<HmLog> {
24        let path = Path::new(path_str);
25        if path.exists() {
26            fs::remove_dir_all(path).unwrap();
27        }
28        fs::create_dir(path_str).unwrap();
29        MyLog {
30            path: path_str.to_string(),
31            io: HashMap::new()
32        }
33    }
34}
35
36impl MyLog<File> {
37    pub fn info_file(&mut self, data: &str) {
38        self.io.write_fmt(format_args!("{:.23} {}\n", Local::now().to_string(), data)).unwrap();
39    }
40}
41
42impl MyLog<HmLog> {
43    pub fn info_dir<T: std::fmt::Display>(&self, file: T, data: &str) {
44        let mut k = self.io.get(&(file.to_string())).unwrap().lock().unwrap();
45        k.write_fmt(format_args!("{:.23} {}\n", Local::now().to_string(), data)).unwrap();
46    }
47    pub fn create_file(&mut self, file_name: &str) {
48        let file = File::create(format!("{}/{}.log", self.path, file_name)).unwrap();
49        self.io.insert(file_name.to_string(), Mutex::new(file));
50    }
51}