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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
extern crate chrono;

use std::error::Error;
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::Write;
use std::string::ToString;

use log_file_config::LogFileConfig;

/// TODO
struct FileAttr {
    write: bool,
    append: bool,
    create: bool,
    truncate: bool,
}

/// TODO
impl FileAttr {
    pub fn new() -> FileAttr {
        return FileAttr {
            write: true,
            append: true,
            create: true,
            truncate: false,
        };
    }
}

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

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

impl LogFile {
    ///
    /// Creates a new Logfile.
    ///
    /// # Example 1
    /// ```rust
    /// extern crate easylog;
    ///
    /// use easylog::{LogFile, LogFileConfig, LogLevel};
    ///
    /// fn main() {
    ///     let default = LogFileConfig::new();
    ///     let logfile = match LogFile::new(default) {
    ///         Ok(file) => file,
    ///
    ///         Err(error) => {
    ///             panic!("Error: `{}`", error);
    ///         }
    ///     };
    /// }
    /// ```
    ///
    /// 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.path = String::from("./path/to/logfile/");
    ///     custom_config.name = String::from("my_logfile");
    ///     custom_config.extension = String::from(".txt");
    ///     custom_config.num_files_to_keep = 2;
    ///
    ///     let logfile = match LogFile::new(custom_config) {
    ///         Ok(file) => file,
    ///
    ///         Err(error) => {
    ///             panic!("Error: `{}`", error);
    ///         }
    ///     };
    /// }
    /// ```
    ///
    /// # Example 3
    /// ```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.path = String::from("./path/to/logfile/");
    ///     custom_config.name = String::from("my_logfile");
    ///     custom_config.extension = String::from(".txt");
    ///     custom_config.overwrite = false;
    ///     custom_config.num_files_to_keep = 1337; // has no effect, because overwrite is false
    ///
    ///     let logfile = match LogFile::new(custom_config) {
    ///         Ok(file) => file,
    ///
    ///         Err(error) => {
    ///             panic!("Error: `{}`", error);
    ///         }
    ///     };
    /// }
    /// ```
    ///
    /// # 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.
    ///
    /// If max_size_in_mb is set to 0 (zero) it will be set to 1. So 1 Megabyte
    /// (1 * 1024 * 1024) is the smallest size for a Logfile.
    ///
    /// If the overwrite param is set to true (default) and num_files_to_keep
    /// (default value is 5) is reached, the first logfile will be overwritten
    /// instead of creating a new one. So you will always have only num_files_to_keep
    /// of logfiles. If overwrite is set to false then you will get as much files as
    /// your machine allows.
    ///
    /// If num_files_to_keep is set to 0 (zero) it will be set to 1. So 1 Logfile
    /// is the smallest amount of Logfiles.
    ///
    pub fn new(mut config: LogFileConfig) -> Result<LogFile, Box<Error>> {
        if config.max_size_in_mb == 0 {
            config.max_size_in_mb = 1;
        }

        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);
            }
        }

        if config.num_files_to_keep == 0 {
            config.num_files_to_keep = 1;
        }

        if config.overwrite && counter > config.num_files_to_keep {
            counter -= config.num_files_to_keep;
        };

        let default_file_attr = FileAttr::new();
        let logfile = open(max_size, config, counter, default_file_attr)?;

        return Ok(logfile);
    }

    ///
    /// Write the given message to the logfile.
    ///
    /// # Example
    /// ```rust
    /// extern crate easylog;
    ///
    /// use easylog::{LogFile, LogFileConfig, LogLevel};
    ///
    /// fn main() {
    ///     let default = LogFileConfig::new();
    ///     let mut logfile = match LogFile::new(default) {
    ///         Ok(file) => file,
    ///
    ///         Err(error) => {
    ///             panic!("Error: `{}`", error);
    ///         }
    ///     };
    ///
    ///     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.
    ///
    pub fn write(&mut self, level: LogLevel, msg: &str) {
        let log_msg = self.prepare_log_msg(level, msg);

        let log_size = self.get_logsize();

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

        self._write(log_msg);
    }

    /// Returns a copy (clone) of the actual object state
    pub fn clone(&mut self) -> LogFile {
        return LogFile {
            max_size: self.max_size.clone(),
            config: self.config.clone(),
            complete_path: self.complete_path.clone(),
            counter: self.counter.clone(),
            file: self.file.try_clone().unwrap(),
        };
    }

    fn _write(&mut self, msg: String) {
        self.file.write(&msg.into_bytes()).unwrap();
        self.file.flush().unwrap();
    }

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

    fn rotate(&mut self) {
        let mut file_attr = FileAttr::new();

        if self.config.overwrite {
            if self.counter == self.config.num_files_to_keep - 1 {
                self.counter -= self.config.num_files_to_keep - 1;
            } else {
                self.counter += 1;
            };
            file_attr.append = false;
            file_attr.truncate = self.config.truncate;
        } else {
            self.counter += 1;
        };

        self.complete_path = assemble_path(&self.config, self.counter);

        self.file = match open_file(&self.complete_path, file_attr) {
            Ok(file) => file,

            Err(error) => {
                let msg = format!(
                    "Could not open new log-file `{}`!  Reason: `{}`",
                    self.complete_path, error
                );
                let msg = self.prepare_log_msg(LogLevel::CRITICAL, &msg);

                self._write(msg);
                self.close();

                panic!("panic while rotating files: `{}`", error);
            }
        };
    }

    fn get_logsize(&self) -> u64 {
        let meta = self.file.metadata().unwrap();

        return meta.len();
    }

    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 prepare_log_msg(&self, level: LogLevel, msg: &str) -> String {
        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');

        return log_msg;
    }
}

fn open(
    max_size: u64,
    config: LogFileConfig,
    counter: u64,
    file_attr: FileAttr,
) -> Result<LogFile, Box<Error>> {
    let path = assemble_path(&config, counter);
    let f = open_file(&path, file_attr)?;

    return Ok(LogFile {
        max_size,
        config,
        complete_path: path.clone().to_string(),
        counter,
        file: f,
    });
}

fn open_file(path: &str, attr: FileAttr) -> Result<File, Box<Error>> {
    let f = OpenOptions::new()
        .write(attr.write)
        .append(attr.append)
        .create(attr.create)
        .truncate(attr.truncate)
        .open(path)?;

    return Ok(f);
}

// 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 path = format!(
        "{}{}{}{}",
        config.path,
        config.name,
        counter.to_string(),
        config.extension
    );

    return path;
}

fn is_size_ok(path: &str, max_size: u64) -> bool {
    let mut check = false;

    match fs::metadata(path) {
        Ok(meta) => {
            if meta.len() < max_size {
                check = true;
            }
        }

        Err(error) => {
            panic!("Something went wrong while checking size!\n`{}`\n", error);
        }
    };

    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("none_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 = "Something went wrong while checking size!")]
    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 = match LogFile::new(default) {
            Ok(file) => file,

            Err(error) => {
                panic!("Error: `{}`", error);
            }
        };

        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]  "
        );
    }

/*
// commented out, becaus it writes 5 MB to the path. maybe not everyone like
// that behavior. so this test will be disabled for the moment
    #[test]
    fn rotating_test() {
        const TO_KEEP: u64 = 3;
        let mut custom_conf = LogFileConfig::new();
        custom_conf.num_files_to_keep = TO_KEEP;

        let mut logfile = match LogFile::new(custom_conf) {
            Ok(file) => file,

            Err(error) => {
                panic!("Error: `{}`", error);
            }
        };

        for _ in 0..200_000 {
            logfile.write(LogLevel::DEBUG, "~(^-^)~");
        }

        assert!(logfile.counter <= TO_KEEP);
    }
*/
}