~james/core

core/shuttle/src/logging.rs -rw-r--r-- 1.2 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 14 hours 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
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use tracing_subscriber::EnvFilter;
use tracing_subscriber::fmt::MakeWriter;

pub fn init() {
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(ConsoleAndStderr)
        .init();
}

#[derive(Clone, Copy, Debug)]
struct ConsoleAndStderr;

struct TeeWriter {
    stderr: io::Stderr,
    console: Option<File>,
}

impl<'a> MakeWriter<'a> for ConsoleAndStderr {
    type Writer = TeeWriter;

    fn make_writer(&'a self) -> Self::Writer {
        TeeWriter {
            stderr: io::stderr(),
            console: OpenOptions::new().write(true).open("/dev/console").ok(),
        }
    }
}

impl Write for TeeWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.stderr.write_all(buf)?;
        if let Some(console) = &mut self.console {
            console.write_all(buf)?;
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        self.stderr.flush()?;
        if let Some(console) = &mut self.console {
            console.flush()?;
        }
        Ok(())
    }
}