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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use std::fmt;
use std::fs::OpenOptions;
use std::io::prelude::*;
use str_util::empty_string;

/// All possible tags which are applied to log entries.
const TAGS: [&str; 4] = ["[info]", "[debug]", "[warning]", "[error]"];
const CLEAR_THRESHOLD: usize = 8192;

/// A complete log entry.
#[derive(Debug, Clone)]
struct Entry {
    level: usize,
    message: String,
}

impl Entry {
    /// Create a new Entry structure.
    #[inline]
    fn new(level: usize, message: String) -> Entry {
        Entry {
            level: level,
            message: message,
        }
    }

    /// Render the Entry to a String for display.
    #[inline]
    fn render(&self) -> String {
        format!("{} {}", TAGS[self.level], self.message)
    }
}

/// A basic log structure containing a vector of entries.
#[derive(Debug)]
pub struct Log {
    log: Vec<Entry>,
    write_status: u32,
    log_file: String,
}

impl Log {
    /// Create a new Log structure.
    #[inline]
    pub fn new() -> Log {
        Log {
            log: Vec::new(),
            write_status: 0,
            log_file: empty_string(),
        }
    }

    /// Add an entry to the log.
    #[inline]
    fn add_entry(&mut self, level: usize, message: String) {
        if self.log.len() > CLEAR_THRESHOLD {
            self.clear();
        }

        let entry = Entry::new(level, message);
        let log_len: usize = self.log.len();
        self.log.push(entry.clone());

        match self.write_status {
            1 => {
                println!("{}", entry.render());
            }
            2 => {
                self.save_entry(log_len);
            }
            3 => {
                println!("{}", entry.render());
                self.save_entry(log_len);
            }
            _ => {}
        }
    }

    fn save_entry(&self, index: usize) {
        let entry: String = self.log[index].render();

        let mut handle = OpenOptions::new()
            .write(true)
            .append(true)
            .create(true)
            .open(&self.log_file)
            .unwrap();

        let _ = writeln!(&mut handle, "{}", entry);
    }

    /// Set the file which log entries will be written to.
    #[inline]
    pub fn set_log_file(&mut self, log_path: String) {
        self.log_file = log_path;
    }

    #[inline]
    pub fn info(&mut self, message: String) {
        self.add_entry(0, message);
    }

    #[inline]
    pub fn debug(&mut self, message: String) {
        self.add_entry(1, message);
    }

    #[inline]
    pub fn warning(&mut self, message: String) {
        self.add_entry(2, message);
    }

    #[inline]
    pub fn error(&mut self, message: String) {
        self.add_entry(3, message);
    }

    /** Set the write status of the log. This dictates what and how stuff is logged. Must be a value between 0-3. Below
    is a list of what the values mean. Note that all modes write the log to memory.

    0 # Log entries are written to memory but nothing else.

    1 # Log entries are automatically printed as they are created.

    2 # Log entries are written to a set file as they are created.

    3 # Mode 3 is a combination of mode 1 and 2. */
    #[inline]
    pub fn set_write(&mut self, mode: u32) {
        self.write_status = mode;
    }

    /// Clear all entries in the log.
    #[inline]
    pub fn clear(&mut self) {
        self.log.clear();
    }

    /// Render the log to a vector of strings.
    pub fn render(&self) -> Vec<String> {
        let mut textlog: Vec<String> = Vec::new();

        for entry in &self.log {
            textlog.push(format!("{} {}", TAGS[entry.level], entry.message));
        }

        textlog
    }
}

impl fmt::Display for Entry {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "{}", &self.render())?;
        Ok(())
    }
}

impl fmt::Display for Log {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for line in &self.render() {
            writeln!(f, "{}", line)?;
        }
        Ok(())
    }
}