~zethra/stargazer

ref: fbbf828c33087d1601d81db7c99c41d71fcb930f stargazer/src/logger.rs -rw-r--r-- 4.0 KiB
fbbf828c — Ben Aaron Goldberg config: add bad config for testing 2 months ago
                                                                                
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
// stargazer - A Gemini Server
// Copyright (C) 2021 Ben Aaron Goldberg <ben@benaaron.dev>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use colored::Colorize;
use crossbeam_channel::{self as chan, Sender};
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
use std::{
    io::{self, Write},
    thread,
};

enum Channel {
    StdOut,
    StdErr,
}

pub struct Logger {
    _shutdown: Sender<()>,
    message_queue: Sender<Option<(String, Channel)>>,
}

pub fn init(log_level: LevelFilter) -> Result<(), SetLoggerError> {
    let (_shutdown, s): (Sender<()>, _) = chan::bounded(0);
    let (message_queue, m): (Sender<Option<(String, Channel)>>, _) =
        chan::unbounded();

    thread::Builder::new()
        .name("stargazer-logger".into())
        .spawn(move || {
            let mut stderr = io::stderr();
            let mut stdout = io::stdout();
            while !s.try_recv().unwrap_err().is_disconnected() {
                while let Ok(op) = m.recv() {
                    match op {
                        Some((mut msg, channel)) => {
                            if !msg.ends_with('\n') {
                                msg.push('\n');
                            }
                            match channel {
                                Channel::StdOut => stdout
                                    .write_all(msg.as_bytes())
                                    .expect("Error writing to stdout"),
                                Channel::StdErr => stderr
                                    .write_all(msg.as_bytes())
                                    .expect("Error writing to stderr"),
                            }
                        }
                        None => {
                            stdout.flush().expect("Error flushing stdout");
                            stderr.flush().expect("Error flushing stderr");
                        }
                    }
                }
            }
        })
        .expect("Error starting logger thread");

    let logger = Logger {
        _shutdown,
        message_queue,
    };
    log::set_boxed_logger(Box::new(logger))
        .map(|()| log::set_max_level(log_level))
}

impl Log for Logger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        metadata.target().starts_with("stargazer")
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            let level = match record.level() {
                Level::Error => Level::Error.to_string().red(),
                Level::Debug => Level::Debug.to_string().yellow(),
                level => level.to_string().normal(),
            };
            let channel = match record.level() {
                Level::Info => Channel::StdOut,
                _ => Channel::StdErr,
            };
            let msg = format!("{} - {}", level, record.args());
            self.message_queue
                .send(Some((msg, channel)))
                .expect("Logger thread isn't running");
        }
    }

    fn flush(&self) {
        // Wait for the message queue empty
        while !self.message_queue.is_empty() {}
        // Tell the logger to flush
        self.message_queue.send(None).unwrap();
        // This should make sure that the first flush finished before the function returns
        while !self.message_queue.is_empty() {}
        self.message_queue.send(None).unwrap();
        while !self.message_queue.is_empty() {}
    }
}