Skip to content

Commit

Permalink
Improve logging
Browse files Browse the repository at this point in the history
  • Loading branch information
WilliamRagstad committed Oct 11, 2023
1 parent 8c04b5a commit 61bad9e
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 30 deletions.
16 changes: 8 additions & 8 deletions src/engine/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{sync::mpsc::Receiver, path::PathBuf, net::{SocketAddr, TcpListener}, io::{Read, Write}};

use crate::{file::webx::WXModule, runner::WXMode};
use crate::{file::webx::WXModule, runner::WXMode, reporting::debug::info};

pub enum WXRuntimeMessage {
NewModule(WXModule),
Expand Down Expand Up @@ -29,7 +29,7 @@ impl WXRuntime {
}

pub fn run(&mut self) {
println!("Runtime started, waiting for module updates and HTTP requests");
info(self.mode, "Runtime started, waiting for module updates and HTTP requests");
let addrs = [
SocketAddr::from(([127, 0, 0, 1], 8080)), // TODO: Only in dev mode
SocketAddr::from(([127, 0, 0, 1], 80)), // TODO: Only in prod mode
Expand All @@ -42,7 +42,7 @@ impl WXRuntime {
if !self.sync_channel_messages() { break } // Exit if requested
// Listen for requests
if let Ok((mut stream, addr)) = listener.accept() /* Blocking */ {
println!("Runtime received request from {}", addr);
info(self.mode, &format!("Runtime received request from {}", addr));
let mut buf = [0; 1024];
stream.read(&mut buf).unwrap();
let response = b"HTTP/1.1 200 OK\r\n\r\nHello, world!";
Expand All @@ -63,23 +63,23 @@ impl WXRuntime {
while let Ok(msg) = self.modules_rx.try_recv() /* Non-blocking */ {
match msg {
WXRuntimeMessage::NewModule(module) => {
println!("Runtime received new module");
info(self.mode, "Runtime received new module");
self.modules.push(module);
},
WXRuntimeMessage::SwapModule(path, module) => {
println!("Runtime received swap module");
info(self.mode, "Runtime received swap module");
self.modules.retain(|m| m.path.inner != path);
self.modules.push(module);
},
WXRuntimeMessage::RemoveModule(path) => {
println!("Runtime received remove module");
info(self.mode, "Runtime received remove module");
self.modules.retain(|m| m.path.inner != path);
},
WXRuntimeMessage::Info(text) => {
println!("Runtime received info: {}", text);
info(self.mode, &format!("Runtime received info: {}", text));
},
WXRuntimeMessage::Exit => {
println!("Runtime received exit");
info(self.mode, "Runtime received exit");
return false;
}
}
Expand Down
9 changes: 9 additions & 0 deletions src/reporting/debug.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use colored::Colorize;

use crate::runner::WXMode;

pub fn info(mode: WXMode, text: &str) {
if mode == WXMode::Dev {
println!("{}: {}", "[INFO]".bright_cyan(), text);
}
}
4 changes: 2 additions & 2 deletions src/reporting/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ fn error_generic(message: String, error_name: &str) {
}

fn exit_error_generic(message: String, code: i32, error_name: &str) -> ! {
error_generic(message, format!("{} ({})", error_name, code_to_name(code)).as_str());
error_generic(message, format!("[{} ({})]", error_name, code_to_name(code)).as_str());
std::process::exit(code);
}

pub fn error(message: String) {
error_generic(message, "Error");
error_generic(message, "[Error]");
}

pub fn exit_error(message: String, code: i32) -> ! {
Expand Down
1 change: 1 addition & 0 deletions src/reporting/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod error;
pub mod warning;
pub mod debug;
4 changes: 2 additions & 2 deletions src/reporting/warning.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use colored::*;

fn warning_generic(message: String, warning_name: &str) {
eprintln!("{} {}", warning_name.yellow(), message);
eprintln!("{}: {}", warning_name.yellow(), message);
}

pub fn warning(message: String) {
warning_generic(message, "Warning");
warning_generic(message, "[Warning]");
}
27 changes: 9 additions & 18 deletions src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ use colored::Colorize;
use notify::{self, Watcher, Error, Event};

use crate::analytics::{dependencies::analyse_module_deps, routes::analyse_module_routes};
use crate::reporting::debug::info;
use crate::engine::runtime::{WXRuntime, WXRuntimeMessage};
use crate::file::parser::parse_webx_file;
use crate::file::webx::WXModule;
use crate::file::project::{load_modules, load_project_config};
use crate::reporting::warning::warning;

const PROJECT_CONFIG_FILE_NAME: &str = "webx.config.json";
static EXIT_FLAG: AtomicBool = AtomicBool::new(false);
Expand Down Expand Up @@ -103,57 +105,46 @@ fn main_loop(source_root: &PathBuf, init_modules: Vec<WXModule>, mode: WXMode) {
let runtime_hnd = std::thread::spawn(move || runtime.run());
// Handle Ctrl+C to exit gracefully
ctrlc::set_handler(move || {
println!("Received Ctrl+C, exiting...");
info(mode, "Received Ctrl+C, exiting...");
EXIT_FLAG.store(true, Relaxed);
rt_tx.send(WXRuntimeMessage::Exit).unwrap();
}).unwrap();
// Check ps info: `ps | ? ProcessName -eq "webx"`
runtime_hnd.join().unwrap();
println!("Runtime thread exited");
info(mode, "Runtime thread exited");
fw_hnd.join().unwrap();
println!("Watcher thread exited");
info(mode, "Watcher thread exited");
}

fn filewatcher(source_root: &PathBuf, rt_tx: Sender<WXRuntimeMessage>) {
let rt_tx_2 = rt_tx.clone();
let mut watcher = notify::recommended_watcher(move |res: Result<Event, Error>| {
match res {
Ok(event) => {
println!("{:?}", event);
match event.kind {
notify::EventKind::Create(_) => {
println!("create");
match parse_webx_file(&event.paths[0]) {
Ok(module) => rt_tx.send(WXRuntimeMessage::NewModule(module)).unwrap(),
Err(e) => println!("watch error: {:?}", e)
Err(e) => warning(format!("watch error: {:?}", e))
}
},
notify::EventKind::Modify(_) => {
println!("modify");
match parse_webx_file(&event.paths[0]) {
Ok(module) => rt_tx.send(WXRuntimeMessage::SwapModule(event.paths[0].clone(), module)).unwrap(),
Err(e) => println!("watch error: {:?}", e)
Err(e) => warning(format!("watch error: {:?}", e))
}
},
notify::EventKind::Remove(_) => {
println!("remove");
rt_tx.send(WXRuntimeMessage::RemoveModule(event.paths[0].clone())).unwrap();
},
_ => {
println!("ignored");
}
_ => ()
}
},
Err(e) => {
println!("watch error: {:?}", e);
}
Err(e) => warning(format!("watch error: {:?}", e))
}
}).unwrap();
watcher.watch(&source_root, notify::RecursiveMode::Recursive).unwrap();
let mut c = 0;
loop {
// rt_tx_2.send(WXRuntimeMessage::Info(format!("Dummy text {}", c))).unwrap();
// c += 1;
std::thread::sleep(std::time::Duration::from_millis(3000));
if EXIT_FLAG.load(Relaxed) { break }
}
Expand Down

0 comments on commit 61bad9e

Please sign in to comment.