Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make cu-consolemon debug pane only active if text_log is true #228

Merged
merged 4 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 48 additions & 24 deletions components/monitors/cu_consolemon/src/debug_pane.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::UI;
use ratatui::layout::Rect;
use ratatui::prelude::Stylize;
use ratatui::widgets::{Block, Borders, Paragraph};
use ratatui::Frame;
use std::sync::atomic::Ordering;
Expand All @@ -12,13 +13,15 @@ use {
std::sync::mpsc::{Receiver, SyncSender},
};

#[derive(Debug)]
pub struct DebugLog {
debug_log: VecDeque<String>,
pub(crate) max_rows: AtomicU16,
rx: Receiver<String>,
}

impl DebugLog {
#[allow(dead_code)]
pub fn new(max_lines: u16) -> (Self, SyncSender<String>) {
let (tx, rx) = std::sync::mpsc::sync_channel(1000);
(
Expand Down Expand Up @@ -69,10 +72,13 @@ pub struct LogSubscriber {
}

impl LogSubscriber {
#[allow(dead_code)]
pub fn new(tx: SyncSender<String>) -> Self {
let log_subscriber = Self { tx };
log::set_boxed_logger(Box::new(log_subscriber.clone())).unwrap();
log::set_max_level(LevelFilter::Info);
if log::set_boxed_logger(Box::new(log_subscriber.clone())).is_err() {
eprintln!("Failed to set `LogSubscriber` as global log subscriber")
}
log::set_max_level(LevelFilter::Debug);
log_subscriber
}

Expand All @@ -90,7 +96,12 @@ impl Log for LogSubscriber {

fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let message = format!("[{}] - {}\n", record.level(), record.args());
let message = format!(
"{} [{}] - {}\n",
chrono::Local::now().time().format("%H:%M:%S"),
record.level(),
record.args()
);

self.push_logs(message);
}
Expand All @@ -107,29 +118,42 @@ pub trait UIExt {

impl UIExt for UI {
fn update_debug_output(&mut self) {
let mut error_buffer = String::new();
self.error_redirect
.read_to_string(&mut error_buffer)
.unwrap();
self.debug_output.push_logs(error_buffer);
self.debug_output.update_logs();
if let Some(debug_output) = self.debug_output.as_mut() {
let mut error_buffer = String::new();
self.error_redirect
.read_to_string(&mut error_buffer)
.unwrap();
debug_output.push_logs(error_buffer);
debug_output.update_logs();
}
}

fn draw_debug_output(&mut self, f: &mut Frame, area: Rect) {
let mut error_buffer = String::new();
self.error_redirect
.read_to_string(&mut error_buffer)
.unwrap();
self.debug_output.push_logs(error_buffer);

let debug_output = self.debug_output.get_logs();

let p = Paragraph::new(debug_output).block(
Block::default()
.title(" Debug Output ")
.title_bottom(format!("{} log entries", self.debug_output.debug_log.len()))
.borders(Borders::ALL),
);
f.render_widget(p, area);
if let Some(debug_output) = self.debug_output.as_mut() {
let mut error_buffer = String::new();
self.error_redirect
.read_to_string(&mut error_buffer)
.unwrap();
debug_output.push_logs(error_buffer);

let debug_log = debug_output.get_logs();

let p = Paragraph::new(debug_log).block(
Block::default()
.title(" Debug Output ")
.title_bottom(format!("{} log entries", debug_output.debug_log.len()))
.borders(Borders::ALL),
);
f.render_widget(p, area);
} else {
#[cfg(debug_assertions)]
let text = "Text logger is disabled";

#[cfg(not(debug_assertions))]
let text = "Only available in dev profile";

let p = Paragraph::new(text.italic());
f.render_widget(p, area);
}
}
}
33 changes: 22 additions & 11 deletions components/monitors/cu_consolemon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ struct UI {
#[cfg(feature = "debug_pane")]
error_redirect: gag::BufferRedirect,
#[cfg(feature = "debug_pane")]
debug_output: debug_pane::DebugLog,
debug_output: Option<debug_pane::DebugLog>,
}

impl UI {
Expand All @@ -306,7 +306,7 @@ impl UI {
task_stats: Arc<Mutex<TaskStats>>,
task_statuses: Arc<Mutex<Vec<TaskStatus>>>,
error_redirect: gag::BufferRedirect,
debug_output: debug_pane::DebugLog,
debug_output: Option<debug_pane::DebugLog>,
) -> UI {
init_error_hooks();
let nodes_scrollable_widget_state =
Expand Down Expand Up @@ -581,7 +581,9 @@ impl UI {

#[cfg(feature = "debug_pane")]
if let Event::Resize(_columns, rows) = event::read()? {
self.debug_output.max_rows.store(rows, Ordering::SeqCst)
if let Some(debug_output) = self.debug_output.as_mut() {
debug_output.max_rows.store(rows, Ordering::SeqCst)
}
}
}
}
Expand Down Expand Up @@ -627,9 +629,6 @@ impl CuMonitor for CuConsoleMon {

#[cfg(feature = "debug_pane")]
{
let max_lines = terminal.size().unwrap().height - 5;
let (debug_log, tx) = debug_pane::DebugLog::new(max_lines);

// redirect stderr, so it doesn't pop in the terminal
let error_redirect = gag::BufferRedirect::stderr().unwrap();

Expand All @@ -639,19 +638,31 @@ impl CuMonitor for CuConsoleMon {
task_stats_ui,
error_states,
error_redirect,
debug_log,
None,
);

#[allow(unused_variables)]
let log_subscriber = debug_pane::LogSubscriber::new(tx);

// Override the cu29-log-runtime Log Subscriber
#[cfg(debug_assertions)]
if cu29_log_runtime::EXTRA_TEXT_LOGGER
.read()
.unwrap()
.is_some()
{
let max_lines = terminal.size().unwrap().height - 5;
let (debug_log, tx) = debug_pane::DebugLog::new(max_lines);

let log_subscriber = debug_pane::LogSubscriber::new(tx);

*cu29_log_runtime::EXTRA_TEXT_LOGGER.write().unwrap() =
Some(Box::new(log_subscriber) as Box<dyn log::Log>);
}

// Set up the terminal again, as there might be some logs which in the console before updating `EXTRA_TEXT_LOGGER`
setup_terminal();

ui.debug_output = Some(debug_log);
} else {
println!("EXTRA_TEXT_LOGGER is none");
}
ui.run_app(&mut terminal).expect("Failed to run app");
}

Expand Down
2 changes: 1 addition & 1 deletion examples/cu_caterpillar/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ fn main() {
let logger_path = tmp_dir.path().join("caterpillar.copper");

let copper_ctx =
basic_copper_setup(&logger_path, SLAB_SIZE, false, None).expect("Failed to setup logger.");
basic_copper_setup(&logger_path, SLAB_SIZE, true, None).expect("Failed to setup logger.");
let mut application = CaterpillarApplicationBuilder::new()
.with_context(&copper_ctx)
.build()
Expand Down
2 changes: 1 addition & 1 deletion examples/cu_rp_balancebot/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fn main() {
}
}

let copper_ctx = basic_copper_setup(&PathBuf::from(logger_path), SLAB_SIZE, false, None)
let copper_ctx = basic_copper_setup(&PathBuf::from(logger_path), SLAB_SIZE, true, None)
.expect("Failed to setup logger.");
debug!("Logger created at {}.", path = logger_path);

Expand Down
2 changes: 1 addition & 1 deletion examples/cu_rp_balancebot/src/resim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ fn main() {
let copper_ctx = basic_copper_setup(
&PathBuf::from(logger_path),
LOG_SLAB_SIZE,
false,
true,
Some(robot_clock.clone()),
)
.expect("Failed to setup logger.");
Expand Down
2 changes: 1 addition & 1 deletion examples/cu_rp_balancebot/src/sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ fn setup_copper(mut commands: Commands) {
let copper_ctx = basic_copper_setup(
&PathBuf::from(logger_path),
LOG_SLAB_SIZE,
false,
true,
Some(robot_clock.clone()),
)
.expect("Failed to setup logger.");
Expand Down
Loading