msgpack_tracing/
lib.rs

1use printer::Printer;
2use restart::RestartableMachine;
3use rotate::Rotate;
4use std::{io, path::Path};
5use storage::Store;
6use string_cache::StringCache;
7use tape::{InstructionSet, TapeMachine, TapeMachineLogger};
8use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt};
9
10pub mod printer;
11pub mod restart;
12pub mod rotate;
13pub mod storage;
14pub mod string_cache;
15pub mod tape;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
18pub enum WithConsole {
19    AnsiColors,
20    PureText,
21    Disabled,
22}
23
24pub fn install_logger<W>(out: W, console: WithConsole)
25where
26    W: io::Write + Send + 'static,
27{
28    do_installer_logger(out_logger(out), console);
29}
30
31pub fn install_rotate_logger<P: AsRef<Path>>(
32    path: P,
33    max_len: u64,
34    console: WithConsole,
35) -> io::Result<()> {
36    let rotate = rotate_logger(path.as_ref(), max_len)?;
37    do_installer_logger(rotate, console);
38    Ok(())
39}
40
41fn do_installer_logger<T>(logger: TapeMachineLogger<T>, console: WithConsole)
42where
43    T: TapeMachine<InstructionSet>,
44{
45    let registry = Registry::default();
46    #[cfg(feature = "env-filter")]
47    let (filter, registry) = {
48        let filter = std::env::var("RUST_LOG").unwrap_or("warn".to_string());
49        let registry = registry.with(tracing_subscriber::EnvFilter::from(&filter));
50        (filter, registry)
51    };
52    #[cfg(not(feature = "env-filter"))]
53    let filter: Option<()> = None;
54
55    let registry = registry.with(logger);
56    let init = match console {
57        console @ WithConsole::AnsiColors | console @ WithConsole::PureText => registry
58            .with(printer_logger(
59                io::stderr(),
60                console == WithConsole::AnsiColors,
61            ))
62            .try_init(),
63        WithConsole::Disabled => registry.try_init(),
64    };
65
66    match init {
67        Ok(()) => tracing::trace!(?filter, ?console, "Logger initialized"),
68        Err(e) => {
69            tracing::warn!(%e, "Trying to initialize logger twice");
70            tracing::debug!(?e);
71        }
72    }
73}
74
75pub fn out_logger<W>(out: W) -> TapeMachineLogger<impl TapeMachine<InstructionSet>>
76where
77    W: io::Write + Send + 'static,
78{
79    TapeMachineLogger::new(StringCache::new(Store::new(out)))
80}
81
82pub fn rotate_logger(
83    path: &Path,
84    max_len: u64,
85) -> io::Result<TapeMachineLogger<impl TapeMachine<InstructionSet>>> {
86    Ok(TapeMachineLogger::new(RestartableMachine::new(
87        StringCache::new(Rotate::new(path, max_len)?),
88    )))
89}
90
91pub fn printer_logger<W>(out: W, color: bool) -> TapeMachineLogger<impl TapeMachine<InstructionSet>>
92where
93    W: io::Write + Send + 'static,
94{
95    TapeMachineLogger::new(Printer::new(out, color))
96}