Use tracing logger

This commit is contained in:
Austen Adler 2023-06-03 23:37:09 -04:00
parent 663fd4feca
commit 76886622ec
8 changed files with 37 additions and 32 deletions

View File

@ -1,4 +1,5 @@
use crossbeam_channel::{select, unbounded, Sender}; use crossbeam_channel::{select, unbounded, Sender};
use tracing::{info, error};
use std::{ use std::{
fs::File, fs::File,
io::Write, io::Write,
@ -35,7 +36,7 @@ impl Cava {
.spawn() .spawn()
.map_err(|e| PatternError::CommandNotFound(e.to_string()))?; .map_err(|e| PatternError::CommandNotFound(e.to_string()))?;
eprintln!("New cava process spawned"); info!("New cava process spawned");
// Send cava stderr to our stderr // Send cava stderr to our stderr
// TODO: Can we just remove the stderr(piped) above? // TODO: Can we just remove the stderr(piped) above?
@ -47,10 +48,10 @@ impl Cava {
Ok(cava_process) Ok(cava_process)
} }
pub fn new(num_bars: u16) -> PatternResult<Self> { pub fn new(num_bars: u16) -> PatternResult<Self> {
eprintln!("Making config file"); info!("Making config file");
let config_file = Self::write_cava_config_file(num_bars as usize * 2)?; let config_file = Self::write_cava_config_file(num_bars as usize * 2)?;
eprintln!("Starting cava"); info!("Starting cava");
let mut cava_process = Self::spawn_cava(&config_file)?; let mut cava_process = Self::spawn_cava(&config_file)?;
// TODO: * 2 because it's a u16 // TODO: * 2 because it's a u16
@ -80,15 +81,15 @@ impl Cava {
true true
} }
recv(reader_error_rx) -> _ => { recv(reader_error_rx) -> _ => {
eprintln!("Cava reader crashed. Will attempt a restart"); error!("Cava reader crashed. Will attempt a restart");
false false
} }
}; };
// We cannot kill a thread. Instead, kill the cava process and expect the threads to die // We cannot kill a thread. Instead, kill the cava process and expect the threads to die
eprintln!("Terminating cava process"); info!("Terminating cava process");
if let Err(e) = cava_process.kill() { if let Err(e) = cava_process.kill() {
eprintln!("Error trying to kill cava process: {e:?}"); error!("Error trying to kill cava process: {e:?}");
} }
if should_terminate { if should_terminate {
@ -101,7 +102,7 @@ impl Cava {
cava_process = match Self::spawn_cava(&config_file) { cava_process = match Self::spawn_cava(&config_file) {
Ok(c) => c, Ok(c) => c,
Err(e) => { Err(e) => {
eprintln!("Could not spawn a new cava process: {e:?}"); error!("Could not spawn a new cava process: {e:?}");
break; break;
} }
} }

View File

@ -1,4 +1,5 @@
use parking_lot::Mutex; use parking_lot::Mutex;
use tracing::{info, error};
use std::io::{Read, Result}; use std::io::{Read, Result};
#[derive(Debug)] #[derive(Debug)]
@ -9,7 +10,7 @@ pub struct FinalRing {
impl FinalRing { impl FinalRing {
pub fn new(size: usize) -> Self { pub fn new(size: usize) -> Self {
eprintln!("Initializing with size: {size}"); info!("Initializing FinalRing with size: {size}");
Self { Self {
size, size,
inner: Mutex::new(vec![0; size]), inner: Mutex::new(vec![0; size]),
@ -24,7 +25,7 @@ impl FinalRing {
let mut buf = vec![0; self.size]; let mut buf = vec![0; self.size];
loop { loop {
if let Err(e) = read.read_exact(&mut buf) { if let Err(e) = read.read_exact(&mut buf) {
eprintln!("Error reading: {e:?}"); error!("Error reading: {e:?}");
break Err(e); break Err(e);
} }

View File

@ -1,4 +1,5 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use tracing::info;
use super::{ColorIterator, FormRender, Pattern, PatternError, PatternResult}; use super::{ColorIterator, FormRender, Pattern, PatternError, PatternResult};
use crate::{ use crate::{
@ -70,7 +71,7 @@ impl Pattern for Visualizer {
self.lights_buf_max = color::stretch(&RAINBOW[..], num_lights as usize).collect(); self.lights_buf_max = color::stretch(&RAINBOW[..], num_lights as usize).collect();
eprintln!("Visualizer got lights buf max: {:?}", self.lights_buf_max); info!("Visualizer got lights buf max: {:?}", self.lights_buf_max);
Ok(()) Ok(())
} }

View File

@ -3,8 +3,6 @@ use submillisecond::{router, static_router, Application};
use submillisecond_live_view::prelude::*; use submillisecond_live_view::prelude::*;
fn main() -> std::io::Result<()> { fn main() -> std::io::Result<()> {
println!("Hello, world!");
Application::new(router! { Application::new(router! {
"/" => Counter::handler("index.html", "#app") "/" => Counter::handler("index.html", "#app")
"/static" => static_router!("./static") "/static" => static_router!("./static")

View File

@ -34,6 +34,7 @@ use common::{
error::{self, ProgramError, ProgramResult}, error::{self, ProgramError, ProgramResult},
strip::Message, strip::Message,
}; };
use tracing::info;
use std::{ use std::{
sync::mpsc::{channel, Sender}, sync::mpsc::{channel, Sender},
thread, thread,
@ -72,8 +73,8 @@ fn main() -> ProgramResult<()> {
loop { loop {
match message_rx.recv() { match message_rx.recv() {
Ok(error::Message::String(s)) => println!("\r{s}"), Ok(error::Message::String(s)) => info!("\r{s}"),
Ok(error::Message::Error(e)) => println!("\rError!! {e:?}"), Ok(error::Message::Error(e)) => info!("\rError!! {e:?}"),
Ok(error::Message::Terminated) => { Ok(error::Message::Terminated) => {
// First, try to turn the strip off // First, try to turn the strip off
let _ = strip_tx.send(Message::Quit); let _ = strip_tx.send(Message::Quit);

View File

@ -13,7 +13,7 @@ pub fn console_ui_loop(
loop { loop {
let line = get_line(message_tx, "Command (cfqs)")?; let line = get_line(message_tx, "Command (cfqs)")?;
if let Err(msg) = parse_cmd(strip_tx, &line) { if let Err(msg) = parse_cmd(strip_tx, &line) {
println!("Command error: {msg}"); error!("Command error: {msg}");
} }
} }
} }

View File

@ -15,3 +15,4 @@ serde_json = "1"
live-view = { path = "./liveview-rust/" } live-view = { path = "./liveview-rust/" }
askama = "0.10.5" askama = "0.10.5"
common = { path = "../common" } common = { path = "../common" }
tracing = "0.1.37"

View File

@ -1,7 +1,9 @@
mod template; mod template;
use actix_web::HttpResponse; use actix_web::HttpResponse;
use actix_web_actors::ws; use actix_web_actors::ws;
use common::{error, pattern, strip}; use common::{ pattern, strip};
use tracing::error;
use tracing::info;
use live_view::{LiveView, StateSocket, Template}; use live_view::{LiveView, StateSocket, Template};
use std::str::FromStr; use std::str::FromStr;
use template::{AppTemplate, ControlTemplate}; use template::{AppTemplate, ControlTemplate};
@ -26,7 +28,7 @@ async fn set_color_json(
data: web::Data<AppState>, data: web::Data<AppState>,
params: web::Json<pattern::Parameters>, params: web::Json<pattern::Parameters>,
) -> Result<impl Responder> { ) -> Result<impl Responder> {
println!("Got params: {params:?}"); info!("Got params: {params:?}");
data.strip_tx data.strip_tx
.lock() .lock()
.map_err(|_| io::Error::new(io::ErrorKind::Other, "Failed to get a lock"))? .map_err(|_| io::Error::new(io::ErrorKind::Other, "Failed to get a lock"))?
@ -37,10 +39,10 @@ async fn set_color_json(
#[actix_web::main] #[actix_web::main]
pub async fn start( pub async fn start(
message_tx: Sender<error::Message>, message_tx: Sender<common::error::Message>,
strip_tx: Sender<strip::Message>, strip_tx: Sender<strip::Message>,
) -> std::io::Result<()> { ) -> std::io::Result<()> {
let _drop = message_tx.send(error::Message::String(String::from("Starting webui"))); let _drop = message_tx.send(common::error::Message::String(String::from("Starting webui")));
HttpServer::new(move || { HttpServer::new(move || {
App::new() App::new()
.data(AppState { .data(AppState {
@ -50,14 +52,14 @@ pub async fn start(
web::scope("/api") web::scope("/api")
.app_data( .app_data(
JsonConfig::default().error_handler(|err: JsonPayloadError, _req| { JsonConfig::default().error_handler(|err: JsonPayloadError, _req| {
// let _drop = message_tx.send(error::Message::String(format!("JSON error: {:?}", err))); // let _drop = message_tx.send(common::error::Message::String(format!("JSON error: {:?}", err)));
println!("JSON error: {err:?}"); error!("JSON error: {err:?}");
err.into() err.into()
}), }),
) )
.app_data(web::FormConfig::default().error_handler( .app_data(web::FormConfig::default().error_handler(
|err: UrlencodedError, _req| { |err: UrlencodedError, _req| {
println!("{err:?}"); error!("{err:?}");
err.into() err.into()
}, },
)) ))
@ -80,7 +82,7 @@ async fn initial_load(data: web::Data<AppState>, _req: HttpRequest) -> impl Resp
} }
.render() .render()
.map_err(|e| { .map_err(|e| {
println!("Internal error e found: {e:?}"); error!("Internal error e found: {e:?}");
ErrorInternalServerError(e) ErrorInternalServerError(e)
})?, })?,
// ..AppTemplate::default() // ..AppTemplate::default()
@ -98,7 +100,7 @@ async fn start_socket(
) -> impl Responder { ) -> impl Responder {
let mut live_view: LiveView<ControlTemplate> = LiveView::default(); let mut live_view: LiveView<ControlTemplate> = LiveView::default();
live_view.on_input("change-template", |event, state| { live_view.on_input("change-template", |event, state| {
println!("Got change template event: {event:?}"); info!("Got change template event: {event:?}");
let template_name = event.data.as_ref()?; let template_name = event.data.as_ref()?;
let params = pattern::Parameters::from_str(template_name).ok()?; let params = pattern::Parameters::from_str(template_name).ok()?;
@ -107,7 +109,7 @@ async fn start_socket(
state state
.render() .render()
.map(|s| { .map(|s| {
println!("{s}"); info!("{s}");
s s
}) })
.map_err(|e| { .map_err(|e| {
@ -118,30 +120,30 @@ async fn start_socket(
}); });
live_view.on_submit("form", |event, state| { live_view.on_submit("form", |event, state| {
// println!("(submit) Form submit: {:?}", event); // info!("(submit) Form submit: {:?}", event);
println!( info!(
"Current value - {:?}", "Current value - {:?}",
serde_json::to_string(&state.parameters) serde_json::to_string(&state.parameters)
); );
println!("Form data: {:?}", event.data); info!("Form data: {:?}", event.data);
let p: pattern::Parameters = serde_json::from_str(event.data.as_ref()?) let p: pattern::Parameters = serde_json::from_str(event.data.as_ref()?)
.map_err(|e| { .map_err(|e| {
eprintln!("Error parsing: {e:?}"); error!("Error parsing: {e:?}");
e e
}) })
.ok()?; .ok()?;
state.parameters = p; state.parameters = p;
println!("Set state parameters to: {:?}", state.parameters); info!("Set state parameters to: {:?}", state.parameters);
state state
.strip_tx .strip_tx
.as_ref()? .as_ref()?
.lock() .lock()
.map_err(|_| { .map_err(|_| {
println!( info!(
"{:?}", "{:?}",
io::Error::new(io::ErrorKind::Other, "Failed to get a lock") io::Error::new(io::ErrorKind::Other, "Failed to get a lock")
) )
@ -149,7 +151,7 @@ async fn start_socket(
.ok()? .ok()?
.send(strip::Message::ChangePattern(state.parameters.to_pattern())) .send(strip::Message::ChangePattern(state.parameters.to_pattern()))
.map_err(|_| { .map_err(|_| {
println!( info!(
"{:?}", "{:?}",
io::Error::new(io::ErrorKind::Other, "Failed to send to channel") io::Error::new(io::ErrorKind::Other, "Failed to send to channel")
) )