Skip to content

Commit

Permalink
add debug logging
Browse files Browse the repository at this point in the history
  • Loading branch information
deepu105 committed Jan 25, 2024
1 parent c18896c commit 5951b76
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 24 deletions.
33 changes: 33 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ glob-match = "0.2.1"
rand = "0.8"
copypasta = "0.10.0"
log = "0.4.14"
simplelog = "0.11.0"
simplelog = "0.12.1"

[dev-dependencies.cargo-husky]
version = "1"
Expand Down
3 changes: 3 additions & 0 deletions src/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ mod utils;
use anyhow::anyhow;
use kube::config::Kubeconfig;
use kubectl_view_allocations::{GroupBy, QtyByQualifier};
use log::{error, info};
use ratatui::layout::Rect;
use tokio::sync::mpsc::Sender;
use tui_input::Input;
Expand Down Expand Up @@ -518,6 +519,7 @@ impl App {
}

pub fn handle_error(&mut self, e: anyhow::Error) {
error!("{:?}", e);
self.api_error = e.to_string();
}

Expand Down Expand Up @@ -591,6 +593,7 @@ impl App {
}

pub async fn cache_all_resource_data(&mut self) {
info!("Caching all resource data");
self.dispatch(IoEvent::GetNamespaces).await;
self.dispatch(IoEvent::GetPods).await;
self.dispatch(IoEvent::DiscoverDynamicRes).await;
Expand Down
3 changes: 3 additions & 0 deletions src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::sync::Arc;

use anyhow::anyhow;
use duct::cmd;
use log::{error, info};
use regex::Regex;
use serde_json::Value as JValue;
use tokio::sync::Mutex;
Expand Down Expand Up @@ -45,6 +46,7 @@ impl<'a> CmdRunner<'a> {
}

async fn handle_error(&self, e: anyhow::Error) {
error!("{:?}", e);
let mut app = self.app.lock().await;
app.handle_error(e);
}
Expand All @@ -57,6 +59,7 @@ impl<'a> CmdRunner<'a> {
.read()
{
Ok(out) => {
info!("kubectl version: {}", out);
let v: serde_json::Result<JValue> = serde_json::from_str(&out);
match v {
Ok(val) => (
Expand Down
85 changes: 63 additions & 22 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ mod event;
mod handlers;
mod network;
mod ui;
mod utils; // Assuming utils.rs exists and contains the setup_logging function

use std::{
fs::File,
io::{self, stdout, Stdout},
panic::{self, PanicInfo},
sync::Arc,
Expand All @@ -18,14 +18,15 @@ use std::{
use anyhow::{anyhow, Result};
use app::App;
use banner::BANNER;
use clap::Parser;
use clap::{builder::PossibleValuesParser, Parser};
use cmd::{CmdRunner, IoCmdEvent};
use crossterm::{
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use event::Key;
use log::{debug, error, info}; // Added for logging
use k8s_openapi::chrono::{self};
use log::{info, warn, LevelFilter, SetLoggerError};
use network::{
get_client,
stream::{IoStreamEvent, NetworkStream},
Expand All @@ -35,6 +36,7 @@ use ratatui::{
backend::{Backend, CrosstermBackend},
Terminal,
};
use simplelog::{Config, WriteLogger};
use tokio::sync::{mpsc, Mutex};

/// kdash CLI
Expand All @@ -51,9 +53,19 @@ pub struct Cli {
/// whether unicode symbols are used to improve the overall look of the app
#[arg(short, long, value_parser, default_value_t = true)]
pub enhanced_graphics: bool,
/// Enable debug mode
#[arg(long, action)]
pub debug: bool,
/// Enables debug mode and writes logs to 'kdash-debug-<timestamp>.log' file in the current directory.
/// Default behavior is to write INFO logs. Pass a log level to overwrite the default.
#[arg(
name = "debug",
short,
long,
default_missing_value = "Info",
require_equals = true,
num_args = 0..=1,
ignore_case = true,
value_parser = PossibleValuesParser::new(&["info", "debug", "trace", "warn", "error"])
)]
pub debug: Option<String>,
}

#[tokio::main]
Expand All @@ -67,9 +79,13 @@ async fn main() -> Result<()> {
let cli = Cli::parse();

// Setup logging if debug flag is set
if cli.debug {
utils::setup_logging()?;
debug!("Debug mode is enabled");
if cli.debug.is_some() {
setup_logging(cli.debug.clone())?;
info!(
"Debug mode is enabled. Level: {}, KDash version: {}",
cli.debug.clone().unwrap(),
env!("CARGO_PKG_VERSION")
);
}

if cli.tick_rate >= 1000 {
Expand Down Expand Up @@ -100,14 +116,17 @@ async fn main() -> Result<()> {

// Launch network thread
std::thread::spawn(move || {
info!("Starting network thread");
start_network(sync_io_rx, &app_nw);
});
// Launch network thread for streams
std::thread::spawn(move || {
info!("Starting network stream thread");
start_stream_network(sync_io_stream_rx, &app_stream);
});
// Launch thread for cmd runner
std::thread::spawn(move || {
info!("Starting cmd runner thread");
start_cmd_runner(sync_io_cmd_rx, &app_cli);
});
// Launch the UI asynchronously
Expand All @@ -124,13 +143,13 @@ async fn start_network(mut io_rx: mpsc::Receiver<IoEvent>, app: &Arc<Mutex<App>>
let mut network = Network::new(client, app);

while let Some(io_event) = io_rx.recv().await {
info!("Network event received: {:?}", io_event);
network.handle_network_event(io_event).await;
}
}
Err(e) => {
let mut app = app.lock().await;
app.handle_error(anyhow!("Unable to obtain Kubernetes client. {:?}", e));
error!("Unable to obtain Kubernetes client: {:?}", e); // Added debug statement
}
}
}
Expand All @@ -142,13 +161,13 @@ async fn start_stream_network(mut io_rx: mpsc::Receiver<IoStreamEvent>, app: &Ar
let mut network = NetworkStream::new(client, app);

while let Some(io_event) = io_rx.recv().await {
info!("Network stream event received: {:?}", io_event);
network.handle_network_stream_event(io_event).await;
}
}
Err(e) => {
let mut app = app.lock().await;
app.handle_error(anyhow!("Unable to obtain Kubernetes client. {:?}", e));
error!("Unable to obtain Kubernetes client: {:?}", e); // Added debug statement
}
}
}
Expand All @@ -158,11 +177,13 @@ async fn start_cmd_runner(mut io_rx: mpsc::Receiver<IoCmdEvent>, app: &Arc<Mutex
let mut cmd = CmdRunner::new(app);

while let Some(io_event) = io_rx.recv().await {
info!("Cmd event received: {:?}", io_event);
cmd.handle_cmd_event(io_event).await;
}
}

async fn start_ui(cli: Cli, app: &Arc<Mutex<App>>) -> Result<()> {
info!("Starting UI");
// see https://docs.rs/crossterm/0.17.7/crossterm/terminal/#raw-mode
enable_raw_mode()?;
// Terminal initialization
Expand All @@ -185,14 +206,6 @@ async fn start_ui(cli: Cli, app: &Arc<Mutex<App>>) -> Result<()> {
// Reset the help menu if the terminal was resized
if app.refresh || app.size != size {
app.size = size;

// Based on the size of the terminal, adjust how many cols are
// displayed in the tables
if app.size.width > 8 {
app.table_cols = app.size.width - 1;
} else {
app.table_cols = 2;
}
}
};

Expand All @@ -202,6 +215,7 @@ async fn start_ui(cli: Cli, app: &Arc<Mutex<App>>) -> Result<()> {
// handle key events
match events.next()? {
event::Event::Input(key_event) => {
info!("Input event received: {:?}", key_event);
// quit on CTRL + C
let key = Key::from(key_event);

Expand All @@ -228,18 +242,40 @@ async fn start_ui(cli: Cli, app: &Arc<Mutex<App>>) -> Result<()> {

terminal.show_cursor()?;
shutdown(terminal)?;

Ok(())
}

// shutdown the CLI and show terminal
fn shutdown(mut terminal: Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
info!("Shutting down");
disable_raw_mode()?;
execute!(terminal.backend_mut(), LeaveAlternateScreen,)?;
execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
terminal.show_cursor()?;
Ok(())
}

fn setup_logging(debug: Option<String>) -> Result<(), SetLoggerError> {
let log_file = format!(
"./kdash-debug-{}.log",
chrono::Local::now().format("%Y%m%d%H%M%S")
);
let log_level = debug
.map(|level| match level.to_lowercase().as_str() {
"debug" => LevelFilter::Debug,
"trace" => LevelFilter::Trace,
"warn" => LevelFilter::Warn,
"error" => LevelFilter::Error,
_ => LevelFilter::Info,
})
.unwrap_or_else(|| LevelFilter::Info);

WriteLogger::init(
log_level,
Config::default(),
File::create(log_file).unwrap(),
)
}

#[cfg(debug_assertions)]
fn panic_hook(info: &PanicInfo<'_>) {
use backtrace::Backtrace;
Expand Down Expand Up @@ -275,6 +311,11 @@ fn panic_hook(info: &PanicInfo<'_>) {
let file_path = handle_dump(&meta, info);
let (msg, location) = get_panic_info(info);

error!(
"thread '<unnamed>' panicked at '{}', {}\n\r{}",
msg, location, stacktrace
);

disable_raw_mode().unwrap();
execute!(
io::stdout(),
Expand All @@ -297,4 +338,4 @@ fn get_panic_info(info: &PanicInfo<'_>) -> (String, String) {
};

(msg.to_string(), format!("{}", location))
}
}
Loading

0 comments on commit 5951b76

Please sign in to comment.