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
use crate::deferred_now::DeferredNow;
use crate::logger::Duplicate;
use crate::writers::LogWriter;
use crate::FormatFunction;
use log::Record;
use std::cell::RefCell;
use std::io::{BufWriter, Write};
use std::sync::Mutex;

// Writes either to stdout, or to stderr,
// or to a file (with optional duplication to stderr),
// or to nowhere (with optional "duplication" to stderr).
#[allow(clippy::large_enum_variant)]
pub(crate) enum PrimaryWriter {
    StdOut(StdOutWriter),
    StdErr(StdErrWriter),
    Multi(MultiWriter),
}
impl PrimaryWriter {
    pub fn multi(
        duplicate_stderr: Duplicate,
        duplicate_stdout: Duplicate,
        format_for_stderr: FormatFunction,
        format_for_stdout: FormatFunction,
        writers: Vec<Box<dyn LogWriter>>,
    ) -> Self {
        Self::Multi(MultiWriter {
            duplicate_stderr,
            duplicate_stdout,
            format_for_stderr,
            format_for_stdout,
            writers,
        })
    }
    pub fn stderr(format: FormatFunction, o_buffer_capacity: &Option<usize>) -> Self {
        Self::StdErr(StdErrWriter::new(format, o_buffer_capacity))
    }

    pub fn stdout(format: FormatFunction, o_buffer_capacity: &Option<usize>) -> Self {
        Self::StdOut(StdOutWriter::new(format, o_buffer_capacity))
    }

    pub fn black_hole(
        duplicate_err: Duplicate,
        duplicate_out: Duplicate,
        format_for_stderr: FormatFunction,
        format_for_stdout: FormatFunction,
    ) -> Self {
        Self::multi(
            duplicate_err,
            duplicate_out,
            format_for_stderr,
            format_for_stdout,
            vec![],
        )
    }

    // Write out a log line.
    pub fn write(&self, now: &mut DeferredNow, record: &Record) -> std::io::Result<()> {
        match *self {
            Self::StdErr(ref w) => w.write(now, record),
            Self::StdOut(ref w) => w.write(now, record),
            Self::Multi(ref w) => w.write(now, record),
        }
    }

    // Flush any buffered records.
    pub fn flush(&self) -> std::io::Result<()> {
        match *self {
            Self::StdErr(ref w) => w.flush(),
            Self::StdOut(ref w) => w.flush(),
            Self::Multi(ref w) => w.flush(),
        }
    }

    pub fn validate_logs(&self, expected: &[(&'static str, &'static str, &'static str)]) {
        if let Self::Multi(ref w) = *self {
            w.validate_logs(expected);
        }
    }
}

// `StdErrWriter` writes logs to stderr.
pub(crate) struct StdErrWriter {
    format: FormatFunction,
    writer: ErrWriter,
}
enum ErrWriter {
    Unbuffered(std::io::Stderr),
    Buffered(Mutex<BufWriter<std::io::Stderr>>),
}
impl StdErrWriter {
    fn new(format: FormatFunction, o_buffer_capacity: &Option<usize>) -> Self {
        match o_buffer_capacity {
            Some(capacity) => Self {
                format,
                writer: ErrWriter::Buffered(Mutex::new(BufWriter::with_capacity(
                    *capacity,
                    std::io::stderr(),
                ))),
            },
            None => Self {
                format,
                writer: ErrWriter::Unbuffered(std::io::stderr()),
            },
        }
    }
    #[inline]
    fn write(&self, now: &mut DeferredNow, record: &Record) -> std::io::Result<()> {
        match &self.writer {
            ErrWriter::Unbuffered(stderr) => {
                let mut w = stderr.lock();
                write_buffered(self.format, now, record, &mut w)
            }
            ErrWriter::Buffered(mbuf_w) => {
                let mut w = mbuf_w.lock().map_err(|e| poison_err("stderr", &e))?;
                write_buffered(self.format, now, record, &mut *w)
            }
        }
    }

    #[inline]
    fn flush(&self) -> std::io::Result<()> {
        match &self.writer {
            ErrWriter::Unbuffered(stderr) => {
                let mut w = stderr.lock();
                w.flush()
            }
            ErrWriter::Buffered(mbuf_w) => {
                let mut w = mbuf_w.lock().map_err(|e| poison_err("stderr", &e))?;
                w.flush()
            }
        }
    }
}

fn poison_err(s: &'static str, _e: &dyn std::error::Error) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::Other, s)
}

// `StdOutWriter` writes logs to stdout.
pub(crate) struct StdOutWriter {
    format: FormatFunction,
    writer: OutWriter,
}
enum OutWriter {
    Unbuffered(std::io::Stdout),
    Buffered(Mutex<BufWriter<std::io::Stdout>>),
}
impl StdOutWriter {
    fn new(format: FormatFunction, o_buffer_capacity: &Option<usize>) -> Self {
        match o_buffer_capacity {
            Some(capacity) => Self {
                format,
                writer: OutWriter::Buffered(Mutex::new(BufWriter::with_capacity(
                    *capacity,
                    std::io::stdout(),
                ))),
            },
            None => Self {
                format,
                writer: OutWriter::Unbuffered(std::io::stdout()),
            },
        }
    }
    #[inline]
    fn write(&self, now: &mut DeferredNow, record: &Record) -> std::io::Result<()> {
        match &self.writer {
            OutWriter::Unbuffered(stdout) => {
                let mut w = stdout.lock();
                write_buffered(self.format, now, record, &mut w)
            }
            OutWriter::Buffered(mbuf_w) => {
                let mut w = mbuf_w.lock().map_err(|e| poison_err("stdout", &e))?;
                write_buffered(self.format, now, record, &mut *w)
            }
        }
    }

    #[inline]
    fn flush(&self) -> std::io::Result<()> {
        match &self.writer {
            OutWriter::Unbuffered(stdout) => {
                let mut w = stdout.lock();
                w.flush()
            }
            OutWriter::Buffered(mbuf_w) => {
                let mut w = mbuf_w.lock().map_err(|e| poison_err("stdout", &e))?;
                w.flush()
            }
        }
    }
}

// The `MultiWriter` writes logs to stderr or to a set of `Writer`s, and in the latter case
// can duplicate messages to stderr.
pub(crate) struct MultiWriter {
    duplicate_stderr: Duplicate,
    duplicate_stdout: Duplicate,
    format_for_stderr: FormatFunction,
    format_for_stdout: FormatFunction,
    writers: Vec<Box<dyn LogWriter>>,
}

impl LogWriter for MultiWriter {
    fn validate_logs(&self, expected: &[(&'static str, &'static str, &'static str)]) {
        for writer in &self.writers {
            (*writer).validate_logs(expected);
        }
    }

    fn write(&self, now: &mut DeferredNow, record: &Record) -> std::io::Result<()> {
        if match self.duplicate_stderr {
            Duplicate::Error => record.level() == log::Level::Error,
            Duplicate::Warn => record.level() <= log::Level::Warn,
            Duplicate::Info => record.level() <= log::Level::Info,
            Duplicate::Debug => record.level() <= log::Level::Debug,
            Duplicate::Trace | Duplicate::All => true,
            Duplicate::None => false,
        } {
            write_buffered(self.format_for_stderr, now, record, &mut std::io::stderr())?;
        }

        if match self.duplicate_stdout {
            Duplicate::Error => record.level() == log::Level::Error,
            Duplicate::Warn => record.level() <= log::Level::Warn,
            Duplicate::Info => record.level() <= log::Level::Info,
            Duplicate::Debug => record.level() <= log::Level::Debug,
            Duplicate::Trace | Duplicate::All => true,
            Duplicate::None => false,
        } {
            write_buffered(self.format_for_stdout, now, record, &mut std::io::stdout())?;
        }

        for writer in &self.writers {
            writer.write(now, record)?;
        }
        Ok(())
    }

    /// Provides the maximum log level that is to be written.
    fn max_log_level(&self) -> log::LevelFilter {
        self.writers
            .iter()
            .map(|w| w.max_log_level())
            .max()
            .unwrap()
    }

    fn flush(&self) -> std::io::Result<()> {
        for writer in &self.writers {
            writer.flush()?;
        }
        if let Duplicate::None = self.duplicate_stderr {
            std::io::stderr().flush()?;
        }
        if let Duplicate::None = self.duplicate_stdout {
            std::io::stdout().flush()?;
        }
        // maybe nicer, but doesn't work with rustc 1.37:
        // if !matches!(self.duplicate_stderr, Duplicate::None) {
        //     std::io::stderr().flush()?;
        // }
        // if !matches!(self.duplicate_stdout, Duplicate::None) {
        //     std::io::stdout().flush()?;
        // }
        Ok(())
    }

    fn shutdown(&self) {
        for writer in &self.writers {
            writer.shutdown();
        }
    }
}

// Use a thread-local buffer for writing to stderr or stdout
fn write_buffered(
    format_function: FormatFunction,
    now: &mut DeferredNow,
    record: &Record,
    w: &mut dyn Write,
) -> Result<(), std::io::Error> {
    let mut result: Result<(), std::io::Error> = Ok(());

    buffer_with(|tl_buf| match tl_buf.try_borrow_mut() {
        Ok(mut buffer) => {
            (format_function)(&mut *buffer, now, record)
                .unwrap_or_else(|e| write_err(ERR_FORMATTING, &e));
            buffer
                .write_all(b"\n")
                .unwrap_or_else(|e| write_err(ERR_FORMATTING, &e));

            result = w.write_all(&*buffer).map_err(|e| {
                write_err(ERR_WRITING, &e);
                e
            });

            buffer.clear();
        }
        Err(_e) => {
            // We arrive here in the rare cases of recursive logging
            // (e.g. log calls in Debug or Display implementations)
            // we print the inner calls, in chronological order, before finally the
            // outer most message is printed
            let mut tmp_buf = Vec::<u8>::with_capacity(200);
            (format_function)(&mut tmp_buf, now, record)
                .unwrap_or_else(|e| write_err(ERR_FORMATTING, &e));
            tmp_buf
                .write_all(b"\n")
                .unwrap_or_else(|e| write_err(ERR_FORMATTING, &e));

            result = w.write_all(&tmp_buf).map_err(|e| {
                write_err(ERR_WRITING, &e);
                e
            });
        }
    });
    result
}

pub(crate) fn buffer_with<F>(f: F)
where
    F: FnOnce(&RefCell<Vec<u8>>),
{
    thread_local! {
        static BUFFER: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(200));
    }
    BUFFER.with(f);
}

const ERR_FORMATTING: &str = "formatting failed with ";
const ERR_WRITING: &str = "writing failed with ";

fn write_err(msg: &str, err: &std::io::Error) {
    eprintln!("[flexi_logger] {} with {}", msg, err);
}