optimization_solvers/
tracer.rs

1use super::*;
2
3pub type BoxedLayer<S> = Box<dyn Layer<S> + Send + Sync>;
4
5#[derive(Default, Copy, Clone)]
6/// Enum with different log formats, passed in the building process
7pub enum LogFormat {
8    /// Pretty format, very detailed (also with line number where log is emitted)
9    Pretty,
10    /// Json format
11    Json,
12    /// Normal format
13    #[default]
14    Normal,
15}
16
17#[derive(Default)]
18pub struct Tracer {
19    std_out_layer: Option<BoxedLayer<Registry>>,
20    journald_layer: Option<BoxedLayer<Registry>>,
21    file_layer: Option<BoxedLayer<Registry>>,
22    _guards: Vec<WorkerGuard>,
23}
24
25impl Tracer {
26    /// Append a layer for write logs to stdout with dedicated thread
27    pub fn with_stdout_layer(mut self, format: Option<LogFormat>) -> Self {
28        let (writer, guard) = tracing_appender::non_blocking(std::io::stdout());
29        let format = format.unwrap_or_default();
30        let std_out_layer: BoxedLayer<Registry> = match format {
31            LogFormat::Pretty => Box::new(fmt::layer().pretty().with_writer(writer)),
32            LogFormat::Json => Box::new(fmt::layer().json().with_writer(writer)),
33            LogFormat::Normal => Box::new(fmt::layer().with_writer(writer)),
34        };
35        self.std_out_layer = Some(std_out_layer);
36        self._guards.push(guard);
37        self
38    }
39
40    pub fn with_normal_stdout_layer(self) -> Self {
41        self.with_stdout_layer(Some(LogFormat::Normal))
42    }
43
44    /// Builds a new Tracer with the layers set in the building steps. Don't drop the guards!
45    pub fn build(self) -> Vec<WorkerGuard> {
46        let env_filter = EnvFilter::from_default_env();
47        let mut layers = vec![];
48        if let Some(std_out_layer) = self.std_out_layer {
49            layers.push(std_out_layer);
50        }
51        if let Some(journald_layer) = self.journald_layer {
52            layers.push(journald_layer);
53        }
54        if let Some(file_layer) = self.file_layer {
55            layers.push(file_layer);
56        }
57        tracing_subscriber::registry()
58            .with(layers)
59            .with(env_filter)
60            .try_init()
61            .ok();
62        self._guards
63    }
64}