feat: improved logging

This commit is contained in:
2025-12-06 02:12:53 -05:00
parent 606880f928
commit 4cdf2db0c9
2 changed files with 26 additions and 23 deletions

View File

@@ -1,3 +1,17 @@
macro_rules! info {
($($arg:tt)*) => {{
print!("info: ");
println!($($arg)*);
}};
}
macro_rules! error {
($($arg:tt)*) => {
eprint!("error: ");
eprintln!($($arg)*);
};
}
mod netutils;
use anywho::Error;
@@ -16,14 +30,14 @@ async fn main() -> Result<(), Error> {
let current_index = Arc::new(Mutex::new(0));
println!("enginewhy starting on 0.0.0.0:8080");
println!("backends: {:?}", backends);
info!("enginewhy starting on 0.0.0.0:8080");
info!("backends: {:?}", backends);
let listener = TcpListener::bind("0.0.0.0:8080").await?;
loop {
let (client, addr) = listener.accept().await?;
println!("info: new connection from {}", addr);
info!("new connection from {}", addr);
let backend = {
let mut index = current_index.lock().await;
@@ -32,10 +46,10 @@ async fn main() -> Result<(), Error> {
selected_backend
};
println!("info: routing client {} to backend {}", addr, backend);
info!("routing client {} to backend {}", addr, backend);
if let Err(e) = tunnel(client, backend).await {
eprintln!("error: proxy failed for {}: {}", addr, e);
error!("proxy failed for {}: {}", addr, e);
}
}
}

View File

@@ -23,14 +23,15 @@ impl fmt::Display for Backend {
pub async fn tunnel(client_stream: TcpStream, backend: Backend) -> Result<(), Box<dyn Error>> {
let backend_address: String = backend.address.clone();
tokio::spawn(async move {
let backend_stream: TcpStream = match TcpStream::connect(&backend_address).await {
Ok(s) => {
println!("Connected to backend {backend_address}");
info!("connected to backend {backend_address}");
s
}
Err(e) => {
eprintln!("Failed connecting to backend {backend_address}: {e}");
error!("failed connecting to backend {backend_address}: {e}");
return;
}
};
@@ -38,23 +39,11 @@ pub async fn tunnel(client_stream: TcpStream, backend: Backend) -> Result<(), Bo
let (mut read_client, mut write_client) = client_stream.into_split();
let (mut read_backend, mut write_backend) = backend_stream.into_split();
let client_to_backend = tokio::spawn(async move {
match io::copy(&mut read_client, &mut write_backend)
.await
.unwrap()
{
n => println!("{n}B ==> backend"),
}
});
let client_to_backend =
tokio::spawn(async move { io::copy(&mut read_client, &mut write_backend).await });
let backend_to_client = tokio::spawn(async move {
match io::copy(&mut read_backend, &mut write_client)
.await
.unwrap()
{
n => println!("{n}B ==> client"),
}
});
let backend_to_client =
tokio::spawn(async move { io::copy(&mut read_backend, &mut write_client).await });
let _ = tokio::join!(client_to_backend, backend_to_client);
});