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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#![crate_name = "easylog"]

extern crate chrono;

use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::string::ToString;


/// Struct to hold the configuration for the logfile
pub struct LogFileConfig {
    /// maximum size for the logfile in MegaBytes
    pub max_size_in_mb: u64,

    /// Path to the file
    pub path: String,

    /// filename
    pub name: String,

    /// fileextension
    pub extension: String,
}


impl LogFileConfig {
    /// Returns a LogFileConfig-struct with default parameters
    pub fn new() -> LogFileConfig {
        return LogFileConfig {
            max_size_in_mb: 1,
            path: String::from("./"),
            name: String::from("logfile_"),
            extension: String::from(".log"),
        };
    }
}


/// Struct that represents the LogFile
pub struct LogFile {
    max_size: u64,
    config: LogFileConfig,
    complete_path: String,
    counter: u64,
    file: File,
}


/// Enum to represent different Loglevel
pub enum LogLevel {
    DEBUG,
    INFO,
    WARNING,
    ERROR,
    CRITICAL,
}


impl LogFile {
    ///
    /// Creates a new Logfile.
    ///
    /// # Example 1
    /// ```rust
    /// extern crate easylog;
    ///
    /// use easylog::{LogFile, LogFileConfig, LogLevel};
    ///
    /// fn main() {
    ///     let default_config = LogFileConfig::new();
    ///     let logfile = LogFile::new(default_config);
    /// }
    /// ```
    ///
    /// You can also modify the config-struct
    ///
    /// # Example 2
    /// ```rust
    /// extern crate easylog;
    ///
    /// use easylog::{LogFile, LogFileConfig, LogLevel};
    ///
    /// fn main() {
    ///     let mut custom_config = LogFileConfig::new();
    ///
    ///     custom_config.max_size_in_mb = 2;
    ///     custom_config.extension = String::from(".txt");
    ///
    ///     let logfile = LogFile::new(custom_config);
    /// }
    /// ```
    ///
    /// # Details
    /// At first this function checks, if already a logfile (specified
    /// by the config argument) exist.
    /// If a logfile exist the size is checked. If the size is okay
    /// (actual size < max size) the file will be opened. When
    /// the size is not okay (actual size > max size) a new file will
    /// be created.
    ///
    pub fn new(config: LogFileConfig) -> LogFile {
        let max_size = config.max_size_in_mb * 1024u64 * 1024u64;

        let mut counter = 0u64;
        let mut path = assemble_path(&config, counter);

        loop {
            let file_exist = check_if_file_exist(&path);
            if !file_exist {
                break;
            }

            let size_ok = is_size_ok(&path, max_size);
            if size_ok {
                break;
            } else {
                counter += 1;
                path = assemble_path(&config, counter);
            }
        }

        let logfile = open(&path, max_size, config, counter);

        return logfile;
    }


    ///
    /// Write the given message to the logfile.
    ///
    /// # Example
    /// ```rust
    /// extern crate easylog;
    ///
    /// use easylog::{LogFile, LogFileConfig, LogLevel};
    ///
    /// fn main() {
    ///     let default_config = LogFileConfig::new();
    ///     let mut logfile = LogFile::new(default_config);
    ///
    ///     logfile.write(LogLevel::DEBUG, "Insert your logmessage here...");
    /// }
    /// ```
    ///
    /// # Example Output
    /// `2018-06-08 20:23:44.278165  [DEBUG   ]  Insert your logmessage here...`
    ///
    /// # Details
    /// The function will append a newline at the end of the message and insert
    /// a timestamp and the given loglevel at the beginning of the message.
    ///
    /// This function also check if the actual logfilesize is less then the allowed
    /// maximum size.
    ///
    /// If the actual logfilesize is bigger as the allowed maximum, the actual
    /// file will be closed, the filecounter will be incresaesed by 1 and a new
    /// file will be opened.
    ///
    /// After writing the message to the file flush will be called to ensure
    /// that all is written to file.
    ///
    /// # Todo
    /// Implementing exception handling when calling file.write() and file.flush()!
    ///
    pub fn write(&mut self, level: LogLevel, msg: &str) {
        let mut log_msg = String::new();

        let time_as_string = get_actual_timestamp();
        log_msg.push_str(&time_as_string);

        let level_as_string = self.get_loglevel_str(level);
        log_msg.push_str(&level_as_string);

        log_msg.push_str(&msg);
        log_msg.push('\n');

        let log_size = self.get_logsize();

        if log_size > self.max_size {
            self.rotate();
        }

        self.file.write(&log_msg.into_bytes()).unwrap(); // TODO:: Handle exceptions
        self.file.flush().unwrap(); // TODO:: Handle exceptions
    }


    fn close(&mut self) {
        drop(&self.file);
    }


    fn rotate(&mut self) {
        self.close();
        self.increase_count();
        self.complete_path = assemble_path(&self.config, self.counter);
        self.file = open_file(&self.complete_path);
    }


    fn get_logsize(&self) -> u64 {
        let meta = self.file.metadata().unwrap(); // TODO:: Handle exceptions

        return meta.len();
    }


    fn increase_count(&mut self) {
        self.counter += 1;
    }


    fn get_loglevel_str(&self, level: LogLevel) -> String {
        let result = match level {
            LogLevel::DEBUG => String::from("  [DEBUG   ]  "),
            LogLevel::INFO => String::from("  [INFO    ]  "),
            LogLevel::WARNING => String::from("  [WARNING ]  "),
            LogLevel::ERROR => String::from("  [ERROR   ]  "),
            LogLevel::CRITICAL => String::from("  [CRITICAL]  "),
        };

        return result;
    }
}


fn open(path: &str, max_size: u64, config: LogFileConfig, counter: u64) -> LogFile {
    return LogFile {
        max_size,
        config,
        complete_path: path.clone().to_string(),
        counter,
        file: open_file(path),
    };
}


fn open_file(path: &str) -> File {
    return OpenOptions::new()
            .write(true)
            .append(true)
            .create(true)
            .open(path)
            .unwrap(); // TODO:: Handle exceptions
}


// https://docs.rs/chrono/0.4.0/chrono/format/strftime/index.html#specifiers
fn get_actual_timestamp() -> String {
    let timestamp = chrono::Local::now();
    let timestamp = timestamp.format("%F %T%.6f").to_string();

    return timestamp;
}


// https://stackoverflow.com/questions/32384594/how-to-check-whether-a-path-exists/32384768#32384768
fn check_if_file_exist(path: &str) -> bool {
    let exist = fs::metadata(path).is_ok();

    return exist;
}


fn assemble_path(config: &LogFileConfig, counter: u64) -> String {
    let mut path = String::new();

    // TODO: need to be refactored
    path.push_str(&config.path);
    path.push_str(&config.name);
    path.push_str(&counter.to_string());
    path.push_str(&config.extension);

    return path;
}


fn is_size_ok(path: &str, max_size: u64) -> bool {
    let meta = fs::metadata(path).unwrap(); // TODO:: Handle exceptions

    let check = if meta.len() < max_size {
        true
    } else {
        false
    };

    return check;
}


#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn assemble_path_test() {
        let default_conf = LogFileConfig::new();
        let counter = 0u64;
        let path = assemble_path(&default_conf, counter);

        assert_eq!(path, "./logfile_0.log");
    }

    #[test]
    fn file_exist_test() {
        assert_eq!(check_if_file_exist("testfile.txt"), true);
        assert_eq!(check_if_file_exist("non_existing_file.txt"), false);
    }

    #[test]
    fn size_is_ok_test() {
        assert_eq!(is_size_ok("testfile.txt", 30), true);
        assert_eq!(is_size_ok("testfile.txt", 20), false);
    }

    #[test]
    #[should_panic(expected = "No such file or directory")]
    fn size_is_not_ok_file_not_exist_test() {
        assert_eq!(is_size_ok("non_existing_file.txt", 20), true);
    }

    #[test]
    fn get_loglevel_str_test() {
        let default = LogFileConfig::new();
        let logfile = LogFile::new(default);

        assert_eq!(logfile.get_loglevel_str(LogLevel::DEBUG), "  [DEBUG   ]  ");
        assert_eq!(logfile.get_loglevel_str(LogLevel::INFO), "  [INFO    ]  ");
        assert_eq!(logfile.get_loglevel_str(LogLevel::WARNING), "  [WARNING ]  ");
        assert_eq!(logfile.get_loglevel_str(LogLevel::ERROR), "  [ERROR   ]  ");
        assert_eq!(logfile.get_loglevel_str(LogLevel::CRITICAL), "  [CRITICAL]  ");
    }
}