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
use std::io::prelude::*;
use std::sync::Mutex;
use std::{io, fmt};

#[cfg(any(target_os = "redox", rustdoc))]
use std::{
    ffi::OsStr,
    fs::{self, File},
    io::BufWriter,
    path::{Path, PathBuf},
};

use smallvec::SmallVec;
use log::{Metadata, Record};

/// An output that will be logged to. The two major outputs for most Redox system programs are
/// usually the log file, and the global stdout.
pub struct Output {
    // the actual endpoint to write to.
    endpoint: Mutex<Box<dyn Write + Send + 'static>>,

    // useful for devices like BufWrite or BufRead. You don't want the log file to never but
    // written until the program exists.
    flush_on_newline: bool,

    // specifies the maximum log level possible
    filter: log::LevelFilter,

    // specifies whether the file should contain ASCII escape codes
    ansi: bool,
}
impl fmt::Debug for Output {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Output")
            .field("endpoint", &"opaque")
            .field("flush_on_newline", &self.flush_on_newline)
            .field("filter", &self.filter)
            .field("ansi", &self.ansi)
            .finish()
    }
}

pub struct OutputBuilder {
    endpoint: Box<dyn Write + Send + 'static>,
    flush_on_newline: Option<bool>,
    filter: Option<log::LevelFilter>,
    ansi: Option<bool>,
}
impl OutputBuilder {
    #[cfg(any(target_os = "redox", rustdoc))]
    pub fn in_redox_logging_scheme<A, B, C>(category: A, subcategory: B, logfile: C) -> Result<Self, io::Error>
    where
        A: AsRef<OsStr>,
        B: AsRef<OsStr>,
        C: AsRef<OsStr>,
    {
        let mut path = PathBuf::from("logging:");
        path.push(category.as_ref());
        path.push(subcategory.as_ref());
        path.push(logfile.as_ref());
        path.set_extension("log");

        if let Some(parent) = path.parent() {
            if !parent.exists() {
                fs::create_dir_all(parent)?;
            }
        }

        Ok(Self::with_endpoint(File::create(path)?))
    }

    pub fn stdout() -> Self {
        Self::with_endpoint(io::stdout())
    }
    pub fn stderr() -> Self {
        Self::with_endpoint(io::stderr())
    }

    pub fn with_endpoint<T>(endpoint: T) -> Self
    where
        T: Write + Send + 'static
    {
        Self::with_dyn_endpoint(Box::new(endpoint))
    }
    pub fn with_dyn_endpoint(endpoint: Box<dyn Write + Send + 'static>) -> Self {
        Self {
            endpoint,
            flush_on_newline: None,
            filter: None,
            ansi: None,
        }
    }
    pub fn flush_on_newline(mut self, flush: bool) -> Self {
        self.flush_on_newline = Some(flush);
        self
    }
    pub fn with_filter(mut self, filter: log::LevelFilter) -> Self {
        self.filter = Some(filter);
        self
    }
    pub fn with_ansi_escape_codes(mut self) -> Self {
        self.ansi = Some(true);
        self
    }
    pub fn build(self) -> Output {
        Output {
            endpoint: Mutex::new(self.endpoint),
            filter: self.filter.unwrap_or(log::LevelFilter::Info),
            flush_on_newline: self.flush_on_newline.unwrap_or(true),
            ansi: self.ansi.unwrap_or(false),
        }
    }
}

const AVG_OUTPUTS: usize = 2;

#[derive(Debug, Default)]
pub struct RedoxLogger {
    outputs: SmallVec<[Output; AVG_OUTPUTS]>,
    min_filter: Option<log::LevelFilter>,
    max_filter: Option<log::LevelFilter>,
    max_level_in_use: Option<log::LevelFilter>,
    min_level_in_use: Option<log::LevelFilter>,
    process_name: Option<String>,
}

impl RedoxLogger {
    pub fn new() -> Self {
        Self::default()
    }
    fn adjust_output_level(max_filter: Option<log::LevelFilter>, min_filter: Option<log::LevelFilter>, max_in_use: &mut Option<log::LevelFilter>, min_in_use: &mut Option<log::LevelFilter>, output: &mut Output) {
        if let Some(max) = max_filter {
            output.filter = std::cmp::max(output.filter, max);
        }
        if let Some(min) = min_filter {
            output.filter = std::cmp::min(output.filter, min);
        }
        match max_in_use {
            &mut Some(ref mut max) => *max = std::cmp::max(output.filter, *max),
            max @ &mut None => *max = Some(output.filter),
        }
        match min_in_use {
            &mut Some(ref mut min) => *min = std::cmp::min(output.filter, *min),
            min @ &mut None => *min = Some(output.filter),
        }
    }
    pub fn with_output(mut self, mut output: Output) -> Self {
        Self::adjust_output_level(self.max_filter, self.min_filter, &mut self.max_level_in_use, &mut self.min_level_in_use, &mut output);
        self.outputs.push(output);
        self
    }
    pub fn with_min_level_override(mut self, min: log::LevelFilter) -> Self {
        self.min_filter = Some(min);
        for output in &mut self.outputs {
            Self::adjust_output_level(self.max_filter, self.min_filter, &mut self.max_level_in_use, &mut self.min_level_in_use, output);
        }
        self
    }
    pub fn with_max_level_override(mut self, max: log::LevelFilter) -> Self {
        self.max_filter = Some(max);
        for output in &mut self.outputs {
            Self::adjust_output_level(self.max_filter, self.min_filter, &mut self.max_level_in_use, &mut self.min_level_in_use, output);
        }
        self
    }
    pub fn with_process_name(mut self, name: String) -> Self {
        self.process_name = Some(name);
        self
    }
    pub fn enable(self) -> Result<&'static Self, log::SetLoggerError> {
        let leak = Box::leak(Box::new(self));
        log::set_logger(leak)?;
        if let Some(max) = leak.max_level_in_use {
            log::set_max_level(max);
        } else {
            log::set_max_level(log::LevelFilter::Off);
        }
        Ok(leak)
    }
    fn write_record<W: Write>(ansi: bool, record: &Record, process_name: Option<&str>, writer: &mut W) -> io::Result<()> {
        use termion::{color, style};
        use log::Level;


        // TODO: Log offloading to another thread or thread pool, maybe?

        let now_local = chrono::Local::now();

        // TODO: Use colors in timezone, when colors are enabled, to e.g. gray out the timezone and
        // make the actual date more readable.
        let time = now_local.format("%Y-%m-%dT%H-%M-%S.%.3f+%:z");
        let target = record.module_path().unwrap_or(record.target());
        let level = record.level();
        let message = record.args();

        let trace_col = color::Fg(color::LightBlack);
        let debug_col = color::Fg(color::White);
        let info_col = color::Fg(color::LightBlue);
        let warn_col = color::Fg(color::LightYellow);
        let err_col = color::Fg(color::LightRed);

        let level_color: &dyn fmt::Display = match level {
            Level::Trace => &trace_col,
            Level::Debug => &debug_col,
            Level::Info => &info_col,
            Level::Warn => &warn_col,
            Level::Error => &err_col,
        };

        let dim_white = color::Fg(color::White);
        let bright_white = color::Fg(color::LightWhite);
        let regular_style = "";
        let bold_style = style::Bold;

        let [message_color, message_style]: [&dyn fmt::Display; 2] = match level {
            Level::Trace | Level::Debug => [&dim_white, &regular_style],
            Level::Info | Level::Warn | Level::Error => [&bright_white, &bold_style],
        };
        let target_color = color::Fg(color::White);

        let time_color = color::Fg(color::LightBlack);

        let reset = color::Fg(color::Reset);

        let show_lines = true;
        let line_number = if show_lines { record.line() } else { None };

        struct LineFmt(Option<u32>, bool);
        impl fmt::Display for LineFmt {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                if let Some(line) = self.0 {
                    if self.1 {
                        // ansi escape codes
                        let col = color::Fg(color::LightBlack);
                        let reset = color::Fg(color::Reset);
                        write!(f, "{col:}:{line:}{reset:}", col=col, line=line, reset=reset)
                    } else {
                        // no ansi escape codes
                        write!(f, ":{}", line)
                    }
                } else {
                    write!(f, "")
                }
            }
        }

        let process_name = process_name.unwrap_or("");

        if ansi {
            writeln!(
                writer,
                "{time:} [{target:}{line:} {level:}] {msg:}",

                time=format_args!("{m:}{col:}{msg:}{rs:}{r:}", m=style::Italic, col=time_color, msg=time, r=reset, rs=style::Reset),
                line=&LineFmt(line_number, true),
                level=format_args!("{m:}{col:}{msg:}{rs:}{r:}", m=style::Bold, col=level_color, msg=level, r=reset, rs=style::Reset),
                target=format_args!("{col:}{process_name:}@{target:}{r:}", col=target_color, process_name=process_name, target=target, r=reset),
                msg=format_args!("{m:}{col:}{msg:}{rs:}{r:}", m=message_style, col=message_color, msg=message, r=reset, rs=style::Reset),
            )
        } else {
            writeln!(
                writer,
                "{time:} [{target:}{line:} {level:}] {msg:}",
                time=time,
                level=level,
                target=format_args!("{process_name}@{target}", process_name=process_name, target=target),
                line=&LineFmt(line_number, false),
                msg=message,
            )
        }
    }
}

impl log::Log for RedoxLogger {
    fn enabled(&self, metadata: &Metadata) -> bool {
        self.max_level_in_use.map(|min| metadata.level() >= min).unwrap_or(false) && self.min_level_in_use.map(|max| metadata.level() <= max).unwrap_or(false)
    }
    fn log(&self, record: &Record) {
        for output in &self.outputs {
            let mut endpoint_guard = match output.endpoint.lock() {
                Ok(e) => e,
                // poison error
                _ => continue,
            };
            if record.metadata().level() <= output.filter {
                let _ = Self::write_record(output.ansi, record, self.process_name.as_deref(), &mut *endpoint_guard);
            }

            if output.flush_on_newline {
                let _ = endpoint_guard.flush();
            }
        }
    }
    fn flush(&self) {
        for output in &self.outputs {
            match output.endpoint.lock() {
                Ok(ref mut e) => { let _ = e.flush(); }
                _ => continue,
            }
        }
    }
}