tui-logger 0.18.2

Logger with smart widget for the `ratatui` crate
Documentation
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use std::{io, sync::mpsc, thread, time};

use log::*;
use ratatui::{prelude::*, widgets::*};
use std::env;
use tui_logger::*;

/// Choose the backend depending on the selected feature (crossterm or termion). This is a mutually
/// exclusive feature, so only one of them can be enabled at a time.
#[cfg(all(feature = "crossterm", not(feature = "termion")))]
use self::crossterm_backend::*;
#[cfg(all(feature = "termion", not(feature = "crossterm")))]
use self::termion_backend::*;
#[cfg(not(any(feature = "crossterm", feature = "termion")))]
compile_error!("One of the features 'crossterm' or 'termion' must be enabled.");
#[cfg(all(feature = "crossterm", feature = "termion"))]
compile_error!("Only one of the features 'crossterm' and 'termion' can be enabled.");

struct App {
    mode: AppMode,
    states: Vec<TuiWidgetState>,
    tab_names: Vec<&'static str>,
    selected_tab: usize,
    progress_counter: Option<u16>,
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum AppMode {
    #[default]
    Run,
    Quit,
}

#[derive(Debug)]
enum AppEvent {
    UiEvent(Event),
    CounterChanged(Option<u16>),
}

//// Example for simple customized formatter
struct MyLogFormatter {}
impl LogFormatter for MyLogFormatter {
    fn min_width(&self) -> u16 {
        4
    }
    fn format(&self, _width: usize, evt: &ExtLogRecord) -> Vec<Line<'_>> {
        let mut lines = vec![];
        match evt.level {
            log::Level::Error => {
                let st = Style::new().red().bold();
                let sp = Span::styled("======", st);
                let mayday = Span::from(" MAYDAY MAYDAY ".to_string());
                let sp2 = Span::styled("======", st);
                lines.push(Line::from(vec![sp, mayday, sp2]).alignment(Alignment::Center));
                lines.push(
                    Line::from(format!("{}: {}", evt.level, evt.msg()))
                        .alignment(Alignment::Center),
                );
            }
            _ => {
                lines.push(Line::from(format!("{}: {}", evt.level, evt.msg())));
            }
        };

        match evt.level {
            log::Level::Error => {
                let st = Style::new().blue().bold();
                let sp = Span::styled("======", st);
                let mayday = Span::from(" MAYDAY SEEN ? ".to_string());
                let sp2 = Span::styled("======", st);
                lines.push(Line::from(vec![sp, mayday, sp2]).alignment(Alignment::Center));
            }
            _ => {}
        };
        lines
    }
}

fn main() {
    init_logger(LevelFilter::Trace).unwrap();
    set_default_level(LevelFilter::Trace);

    let mut dir = env::temp_dir();
    dir.push("tui-logger_demo.log");
    let file_options = TuiLoggerFile::new(dir.to_str().unwrap())
        .output_level(Some(TuiLoggerLevelOutput::Abbreviated))
        .output_file(false)
        .output_separator(':');
    set_log_file(file_options);
    debug!(target:"App", "Logging to {}", dir.to_str().unwrap());
    debug!(target:"App", "Logging initialized");

    let mut terminal = init_terminal().unwrap();
    terminal.clear().unwrap();
    terminal.hide_cursor().unwrap();

    App::new().start(&mut terminal).unwrap();

    restore_terminal().unwrap();
    terminal.clear().unwrap();
}

impl App {
    pub fn new() -> App {
        let states = vec![
            TuiWidgetState::new().set_default_display_level(LevelFilter::Info),
            TuiWidgetState::new().set_default_display_level(LevelFilter::Info),
            TuiWidgetState::new().set_default_display_level(LevelFilter::Info),
            TuiWidgetState::new().set_default_display_level(LevelFilter::Info),
        ];

        // Adding this line had provoked the bug as described in issue #69
        // let states = states.into_iter().map(|s| s.set_level_for_target("some::logger", LevelFilter::Off)).collect();
        let tab_names = vec!["State 1", "State 2", "State 3", "State 4"];
        App {
            mode: AppMode::Run,
            states,
            tab_names,
            selected_tab: 0,
            progress_counter: None,
        }
    }

    pub fn start<B: Backend>(mut self, terminal: &mut Terminal<B>) -> Result<(), B::Error> {
        // Use an mpsc::channel to combine stdin events with app events
        let (tx, rx) = mpsc::channel();
        let event_tx = tx.clone();
        let progress_tx = tx.clone();

        thread::spawn(move || input_thread(event_tx).unwrap());
        thread::spawn(move || progress_task(progress_tx).unwrap());
        thread::spawn(move || background_task());
        thread::spawn(move || background_task2());
        thread::spawn(move || heart_task());

        self.run(terminal, rx)
    }

    /// Main application loop
    fn run<B: Backend>(
        &mut self,
        terminal: &mut Terminal<B>,
        rx: mpsc::Receiver<AppEvent>,
    ) -> Result<(), B::Error> {
        for event in rx {
            match event {
                AppEvent::UiEvent(event) => self.handle_ui_event(event),
                AppEvent::CounterChanged(value) => self.update_progress_bar(event, value),
            }
            if self.mode == AppMode::Quit {
                break;
            }
            self.draw(terminal)?;
        }
        Ok(())
    }

    fn update_progress_bar(&mut self, event: AppEvent, value: Option<u16>) {
        trace!(target: "App", "Updating progress bar {:?}",event);
        self.progress_counter = value;
        if value.is_none() {
            info!(target: "App", "Background task finished");
        }
    }

    fn handle_ui_event(&mut self, event: Event) {
        debug!(target: "App", "Handling UI event: {:?}",event);
        let state = self.selected_state();

        if let Event::Key(key) = event {
            #[cfg(feature = "crossterm")]
            let code = key.code;

            #[cfg(feature = "termion")]
            let code = key;

            match code.into() {
                Key::Char('q') => self.mode = AppMode::Quit,
                Key::Char('\t') => self.next_tab(),
                #[cfg(feature = "crossterm")]
                Key::Tab => self.next_tab(),
                Key::Char(' ') => state.transition(TuiWidgetEvent::SpaceKey),
                Key::Esc => state.transition(TuiWidgetEvent::EscapeKey),
                Key::PageUp => state.transition(TuiWidgetEvent::PrevPageKey),
                Key::PageDown => state.transition(TuiWidgetEvent::NextPageKey),
                Key::Up => state.transition(TuiWidgetEvent::UpKey),
                Key::Down => state.transition(TuiWidgetEvent::DownKey),
                Key::Left => state.transition(TuiWidgetEvent::LeftKey),
                Key::Right => state.transition(TuiWidgetEvent::RightKey),
                Key::Char('+') => state.transition(TuiWidgetEvent::PlusKey),
                Key::Char('-') => state.transition(TuiWidgetEvent::MinusKey),
                Key::Char('h') => state.transition(TuiWidgetEvent::HideKey),
                Key::Char('f') => state.transition(TuiWidgetEvent::FocusKey),
                _ => (),
            }
        }
    }

    fn selected_state(&mut self) -> &mut TuiWidgetState {
        &mut self.states[self.selected_tab]
    }

    fn next_tab(&mut self) {
        self.selected_tab = (self.selected_tab + 1) % self.tab_names.len();
    }

    fn draw<B: Backend>(&mut self, terminal: &mut Terminal<B>) -> Result<(), B::Error> {
        terminal.draw(|frame| {
            frame.render_widget(self, frame.area());
        })?;
        Ok(())
    }
}

/// A simulated task that sends a counter value to the UI ranging from 0 to 100 every second.
fn progress_task(tx: mpsc::Sender<AppEvent>) -> anyhow::Result<()> {
    for progress in 0..100 {
        debug!(target:"progress-task", "Send progress to UI thread. Value: {:?}", progress);
        tx.send(AppEvent::CounterChanged(Some(progress)))?;

        trace!(target:"progress-task", "Sleep one second");
        thread::sleep(time::Duration::from_millis(1000));
    }
    info!(target:"progress-task", "Progress task finished");
    tx.send(AppEvent::CounterChanged(None))?;
    Ok(())
}

/// A background task that logs a log entry for each log level every second.
fn background_task() {
    loop {
        error!(target:"background-task", "an error");
        warn!(target:"background-task", "a warning");
        info!(target:"background-task", "a two line info\nsecond line");
        debug!(target:"background-task", "a debug");
        trace!(target:"background-task", "a trace");
        thread::sleep(time::Duration::from_millis(1000));
    }
}

/// A background task for long line
fn background_task2() {
    loop {
        info!(target:"background-task2", "This is a very long message, which should be wrapped on smaller screen by the standard formatter with an indentation of 9 characters.");
        thread::sleep(time::Duration::from_millis(2000));
    }
}

/// A background task for utf8 example
fn heart_task() {
    let mut line = "♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥".to_string();
    loop {
        info!(target:"heart-task", "{}", line);
        line = format!(".{}", line);
        thread::sleep(time::Duration::from_millis(1500));
    }
}

impl Widget for &mut App {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let progress_height = if self.progress_counter.is_some() {
            3
        } else {
            0
        };
        let [tabs_area, smart_area, main_area, progress_area, help_area] = Layout::vertical([
            Constraint::Length(3),
            Constraint::Fill(50),
            Constraint::Fill(30),
            Constraint::Length(progress_height),
            Constraint::Length(3),
        ])
        .areas(area);
        // show two TuiWidgetState side-by-side
        let [left, right] = Layout::horizontal([Constraint::Fill(1); 2]).areas(main_area);

        Tabs::new(self.tab_names.iter().cloned())
            .block(Block::default().title("States").borders(Borders::ALL))
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED))
            .select(self.selected_tab)
            .render(tabs_area, buf);

        TuiLoggerSmartWidget::default()
            .style_error(Style::default().fg(Color::Red))
            .style_debug(Style::default().fg(Color::Green))
            .style_warn(Style::default().fg(Color::Yellow))
            .style_trace(Style::default().fg(Color::Magenta))
            .style_info(Style::default().fg(Color::Cyan))
            .output_separator(':')
            .output_timestamp(Some("%H:%M:%S".to_string()))
            .output_level(Some(TuiLoggerLevelOutput::Abbreviated))
            .output_target(true)
            .output_file(true)
            .output_line(true)
            .state(self.selected_state())
            .render(smart_area, buf);

        // An example of filtering the log output. The left TuiLoggerWidget is filtered to only show
        // log entries for the "App" target. The right TuiLoggerWidget shows all log entries.
        let filter_state = TuiWidgetState::new()
            .set_default_display_level(LevelFilter::Off)
            .set_level_for_target("App", LevelFilter::Debug)
            .set_level_for_target("background-task", LevelFilter::Info);
        let mut formatter: Option<Box<dyn LogFormatter>> = None;
        if cfg!(feature = "formatter") {
            formatter = Some(Box::new(MyLogFormatter {}));
        }

        TuiLoggerWidget::default()
            .block(Block::bordered().title("Filtered TuiLoggerWidget"))
            .output_separator('|')
            .output_timestamp(Some("%F %H:%M:%S%.3f".to_string()))
            .output_level(Some(TuiLoggerLevelOutput::Long))
            .output_target(false)
            .output_file(false)
            .output_line(false)
            .style(Style::default().fg(Color::White))
            .state(&filter_state)
            .render(left, buf);

        TuiLoggerWidget::default()
            .block(Block::bordered().title("Unfiltered TuiLoggerWidget"))
            .opt_formatter(formatter)
            .output_separator('|')
            .output_timestamp(Some("%F %H:%M:%S%.3f".to_string()))
            .output_level(Some(TuiLoggerLevelOutput::Long))
            .output_target(false)
            .output_file(false)
            .output_line(false)
            .style(Style::default().fg(Color::White))
            .render(right, buf);

        if let Some(percent) = self.progress_counter {
            Gauge::default()
                .block(Block::bordered().title("progress-task"))
                .gauge_style((Color::White, Modifier::ITALIC))
                .percent(percent)
                .render(progress_area, buf);
        }
        if area.width > 40 {
            Text::from(vec![
                "Q: Quit | Tab: Switch state | ↑/↓: Select target | f: Focus target".into(),
                "←/→: Display level | +/-: Filter level | Space: Toggle hidden targets".into(),
                "h: Hide target selector | PageUp/Down: Scroll | Esc: Cancel scroll".into(),
            ])
            .style(Color::Gray)
            .centered()
            .render(help_area, buf);
        }
    }
}

/// A module for crossterm specific code
#[cfg(feature = "crossterm")]
mod crossterm_backend {
    use super::*;

    pub use crossterm::{
        event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode as Key},
        execute,
        terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
    };

    pub fn init_terminal() -> io::Result<Terminal<impl Backend>> {
        trace!(target:"crossterm", "Initializing terminal");
        enable_raw_mode()?;
        execute!(io::stdout(), EnterAlternateScreen, EnableMouseCapture)?;
        let backend = CrosstermBackend::new(io::stdout());
        Terminal::new(backend)
    }

    pub fn restore_terminal() -> io::Result<()> {
        trace!(target:"crossterm", "Restoring terminal");
        disable_raw_mode()?;
        execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture)
    }

    pub fn input_thread(tx_event: mpsc::Sender<AppEvent>) -> anyhow::Result<()> {
        trace!(target:"crossterm", "Starting input thread");
        while let Ok(event) = event::read() {
            trace!(target:"crossterm", "Stdin event received {:?}", event);
            tx_event.send(AppEvent::UiEvent(event))?;
        }
        Ok(())
    }
}

/// A module for termion specific code
#[cfg(feature = "termion")]
mod termion_backend {
    use super::*;
    use termion::screen::IntoAlternateScreen;
    pub use termion::{
        event::{Event, Key},
        input::{MouseTerminal, TermRead},
        raw::IntoRawMode,
    };

    pub fn init_terminal() -> io::Result<Terminal<impl Backend>> {
        trace!(target:"termion", "Initializing terminal");
        let stdout = io::stdout().into_raw_mode()?;
        let stdout = MouseTerminal::from(stdout);
        let stdout = stdout.into_alternate_screen()?;
        let backend = TermionBackend::new(stdout);
        Terminal::new(backend)
    }

    pub fn restore_terminal() -> io::Result<()> {
        trace!(target:"termion", "Restoring terminal");
        Ok(())
    }

    pub fn input_thread(tx_event: mpsc::Sender<AppEvent>) -> anyhow::Result<()> {
        trace!(target:"termion", "Starting input thread");
        for event in io::stdin().events() {
            let event = event?;
            trace!(target:"termion", "Stdin event received {:?}", event);
            tx_event.send(AppEvent::UiEvent(event))?;
        }
        Ok(())
    }
}