forestry 1.11.0

A simple cross-platform CLI logging library for Rust
Documentation
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
#[cfg(not(feature = "async"))]
use std::{fs::File, io::{self, Write}};

#[cfg(feature = "async")]
mod r#async;
#[cfg(feature = "async")]
pub use r#async::*;
#[cfg(feature = "async")]
use tokio::{fs::File, io::{self, AsyncWriteExt}};

use textfmt::*;

/**
    A simple logger for an application.
    
    The logger is used to log messages to the console.
    The messages are coloured based on their severity level.
    Logs are output with a unique 16-bit log index.
    Logger also contains an 8-bit options value set by `cfg()`.
 */
pub struct Logger {
    pub index: u16,
    pub flags: u8,
    pub file: Option<io::BufWriter<File>>,
    pub timer: Option<std::time::Instant>,
}

impl Logger {
    /**
        Create a new logger.
      
        The logger is initialised with a log index of 0.
     */
    pub fn new() -> Self {
        let mut flags = 0;
        if let Some(support) = supports_color::on(supports_color::Stream::Stderr) {
            if !support.has_256 {
                flags |= 0b00001100;
            }
        }
        Logger {
            index: 0,
            flags,
            file: None,
            timer: None,
        }
    }

    fn fmt_header(&self, lvl: LogLevel) -> String {
        // If no part of the header is desired, return a blank string.
        if self.flags & 0b01000011 == 0b00000011 {
            return "".to_string();
        }
        let mut cnt: FmtText = "".into();
        let mut sym: FmtText = "".into();
        let mut tim: FmtText = "".into();

        if self.flags & 0b0001 == 0 {
            cnt = format!("{:0>4x}", self.index).into();
        }
        if self.flags & 0b0010 == 0 {
            sym = match lvl {
                LogLevel::Info => "*".into(),
                LogLevel::Warn => "~".into(),
                LogLevel::Error => "!".into(),
                LogLevel::Success => "+".into(),
                LogLevel::Critical => "%".into(),
                LogLevel::Debug => "?".into(),
            };
        }
        if self.flags & 0b01000000 != 0 {
            let micros = self.timer.unwrap().elapsed().as_micros();
            let msecs = micros as f64 / 1_000.0;
            tim = format!("{:.3}ms", msecs).into();
        }
        if self.flags & 0b0100 == 0 {
            match lvl {
                LogLevel::Info => {
                    cnt = cnt.blue();
                    sym = sym.blue();
                    tim = tim.blue();
                },
                LogLevel::Warn => {
                    cnt = cnt.yellow();
                    sym = sym.yellow();
                    tim = tim.yellow();
                },
                LogLevel::Error => {
                    cnt = cnt.red();
                    sym = sym.red();
                    tim = tim.red();
                },
                LogLevel::Success => {
                    cnt = cnt.green();
                    sym = sym.green();
                    tim = tim.green();
                },
                LogLevel::Critical => {
                    cnt = cnt.bg_red().white();
                    sym = sym.bg_red().white();
                    tim = tim.bg_red().white();
                },
                LogLevel::Debug => {
                    cnt = cnt.magenta();
                    sym = sym.magenta();
                    tim = tim.magenta();
                }
            }
        }
        if self.flags & 0b1000 == 0 {
            cnt = cnt.bold();
            sym = sym.bold();
            tim = tim.bold();
        }
        #[allow(unused_assignments)]
        let mut res = String::from("");
        if self.flags & 0b0011 == 0 {
            let cnt: String = cnt.to_string();
            let sym: String = sym.to_string();
            res.push('[');
            res.push_str(&cnt);
            res.push(':');
            res.push_str(&sym);
            res.push(']');
        } else if self.flags & 0b0001 == 0 {
            let cnt: String = cnt.to_string();
            res.push('[');
            res.push_str(&cnt);
            res.push(']');
        } else {
            let sym: String = sym.to_string();
            res.push('[');
            res.push_str(&sym);
            res.push(']');
        }
        if self.flags & 0b01000000 != 0 {
            let tim: String = tim.to_string();
            res.push('(');
            res.push_str(&tim);
            res.push(')');
        }
        res.push(' ');
        res
    }

    fn fmt_string(&self, lvl: LogLevel, s: &str) -> String {
        let mut fmt: FmtText = s.into();
        if self.flags & 0b0100 == 0 {
            match lvl {
                LogLevel::Info => {
                    fmt = fmt.blue()
                },
                LogLevel::Warn => {
                    fmt = fmt.yellow()
                },
                LogLevel::Error => {
                    fmt = fmt.red()
                },
                LogLevel::Success => {
                    fmt = fmt.green()
                },
                LogLevel::Critical => {
                    fmt = fmt.bg_red().white()
                },
                LogLevel::Debug => {
                    fmt = fmt.magenta()
                }
            }
        }
        if self.flags & 0b1000 == 0 {
            match lvl {
                LogLevel::Error => {
                    fmt = fmt.bold()
                },
                LogLevel::Success => {
                    fmt = fmt.bold()
                },
                LogLevel::Critical => {
                    fmt = fmt.bold()
                },
                _ => {},
            }
        }
        fmt.to_string()
    }
}

#[cfg(not(feature = "async"))]
impl Logger {
    /**
        Configure the logger with options.
        
        See [Options] for more details.
        
        # Arguments
        - `opts`: an array of [Options]
     */
    pub fn cfg(&mut self, opts: &[Options]) -> Result<&mut Self, io::Error> {
        for &e in opts {
            match e {
                Options::NoIndex =>   self.flags |= 0b00000001,
                Options::NoSymbol =>  self.flags |= 0b00000010,
                Options::NoColor =>   self.flags |= 0b00000100,
                Options::NoBold =>    self.flags |= 0b00001000,
                Options::Plain =>     self.flags |= 0b00001100,
                Options::Basic =>     self.flags |= 0b00001111,
                Options::File => {
                    self.flags |= 0b00010000;
                    self.file = Some(
                        io::BufWriter::new(
                        File::create("forestry.log")?)
                    );
                },
                Options::FileAt(f) => {
                    self.flags |= 0b00010000;
                    self.file = Some(
                        io::BufWriter::new(
                        f.try_clone()?)
                    );
                },
                Options::FileOnly =>  self.flags |= 0b00100000,
                Options::Timer => {
                    self.flags |= 0b01000000;
                    self.timer = Some(std::time::Instant::now());
                },
                Options::TimerAt(t) => {
                    self.flags |= 0b01000000;
                    self.timer = Some(*t);
                },
                Options::Reset =>     self.flags &= 0b00000000,
            }
        }
        Ok(self)
    }

    /**
        Log a message.
        
        The message is logged as an INFO message.
        
        # Arguments
        - `s`: The message to log.
        
        # Example
        ```rust
         use forestry::prelude::*;
         let mut log = Logger::new();
         log.info("info");            // Output: [0000:*] info
        ```
     */
    #[inline(always)]
    pub fn info(&mut self, s: &str) -> &mut Self {
        self.print(LogLevel::Info, s)
    }

    /**
        Log a message.
        
        The message is logged as a WARN message.
        
        # Arguments
        - `s`: The message to log.
        
        # Example
        ```rust
         use forestry::prelude::*;
         let mut log = Logger::new();
         log.warn("warn");            // Output: [0000:~] warn
        ```
     */
    #[inline(always)]
    pub fn warn(&mut self, s: &str) -> &mut Self {
        self.print(LogLevel::Warn, s)
    }

    /**
        Log a message.
        
        The message is logged as an ERROR message.
        
        # Arguments
        - `s`: The message to log.
        
        # Example
        ```rust
         use forestry::prelude::*;
         let mut log = Logger::new();
         log.error("error");           // Output: [0000:!] error
        ```
     */
    #[inline(always)]
    pub fn error(&mut self, s: &str) -> &mut Self {
        self.print(LogLevel::Error, s)
    }

    /**
        Log a message.
        
        The message is logged as a SUCCESS message.
        
        # Arguments
        - `s`: The message to log.
        
        # Example
        ```rust
         use forestry::prelude::*;
         let mut log = Logger::new();
         log.success("success");         // Output: [0000:+] success
        ```
     */
    #[inline(always)]
    pub fn success(&mut self, s: &str) -> &mut Self {
        self.print(LogLevel::Success, s)
    }

    /**
        Log a message.

        The message is logged as a CRITICAL message.

        # Arguments
        - `s`: The message to log.

        # Example
        ```rust
         use forestry::prelude::*;
         let mut log = Logger::new();
         log.critical("critical");        // Output: [0000:%] critical
        ```
    */
    #[inline(always)]
    pub fn critical(&mut self, s: &str) -> &mut Self {
        self.print(LogLevel::Critical, s)
    }

    /**
        Log a message.

        The mesage is logged as a DEBUG message.

        # Arguments
        - `s`: The message to log.

        # Example
        ```rust
         use forestry::prelude::*;
         let mut log = Logger::new();
         log.debug("debug");              // Output: [0000:?] debug
        ```
    */
    #[inline(always)]
    pub fn debug(&mut self, s: &str) -> &mut Self {
        self.print(LogLevel::Debug, s);
        self
    }

    fn print(&mut self, lvl: LogLevel, string: &str) -> &mut Self {
        let mut s: String = self.fmt_header(lvl);
        s.push_str(&self.fmt_string(lvl, string));
        s.push('\n');
        if self.flags & 0b00100000 == 0 {
            io::stderr().write_all(s.as_bytes()).unwrap();
        }

        if self.flags & 0b00010000 != 0 {
            let temp = self.flags & 0b00001100;
            self.flags |= 0b00001100;
            let plain = ansi_strip(&s);
            if let Some(inner) = &mut self.file {
                inner
                    .write(plain.as_bytes())
                    .unwrap();
                inner.flush().unwrap();
            } else {
                self.warn("File output enabled without file specified.");
            }
            self.flags &= 0b11110011;
            self.flags |= temp;
        }

        if self.flags & 0b00000001 == 0 {
            self.index = self.index.wrapping_add(1);
            if self.index == 0 {
                self.warn("Log index overflowed; log index may be inaccurate.");
            }
        }
        self
    }
}

/**
    Formatting options for the `Logger`.
    
    - `NoIndex`: Removes the incrementing log index.
    - `NoSymbol`: Removes the log type symbol.
    - `NoColor`: Removes all colour sequences.
    - `NoBold`: Removes all bold sequences.
    - `Plain`: Removes all formatting escape characters.
    - `Basic`: Turns this into a bare `eprintln!()` call.
    - `File`: Logs to the default file (`forestry.log`).
    - `FileAt(&'a std::fs::File)`: Logs to a specified file.
    - `FileOnly`: Only logs to the file; requires `File` or `FileAt`.
    - `Time`: Include a timestamp in the log.
    - `TimerAt (&'a std::time::Instant)`: Attach an existing timestamp to the log (to allow the use of a runtime timer within one's own program as the timer).
    - `Reset`: Resets the logger's formatter to default settings.
 */
#[derive(Copy, Clone)]
pub enum Options <'a> {
    /// Removes the incrementing log index.
    NoIndex,
    /// Removes the log type symbol.
    NoSymbol,
    /// Removes all colours.
    NoColor,
    /// Removes bold/highlighting.
    NoBold,
    /// Removes all formatting escape characters.
    Plain,
    /// Removes all extras; this is now just `eprintln!()`.
    Basic,
    /// Logs to the default file
    File,
    /// Logs to a specified file
    FileAt(&'a File),
    /// Only logs to the file; requires `File` or `FileAt`.
    FileOnly,
    /// Include a timestamp in the log.
    Timer,
    /// Attach an existing timestamp to the log (to allow the use of a runtime timer within one's own program as the timer).
    TimerAt(&'a std::time::Instant),
    /// Reset the logger's formatter to its default state.
    Reset,
}

#[derive(Clone, Copy)]
enum LogLevel {
    Info,
    Warn,
    Error,
    Success,
    Critical,
    Debug,
}

fn ansi_strip(s: &str) -> String {
    if !s.contains("\x1b[") { return s.to_owned() }
    let mut chars = s.chars();
    let mut buf = String::new();
    while let Some(c) = chars.next() {
        match c {
            '\x1b' => {
                // consume up to and including the next 'm'
                while let Some(ch) = chars.next() {
                    if ch == 'm' {break;}
                }
            }
            _ => buf.push(c),
        }
    }
    buf
}