From ad0d6c330c5aea1ffe3a553d5d1d14a513d3cff3 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Sun, 18 Sep 2022 19:46:12 +0200 Subject: [PATCH] tokio-tutorial-mini-redis: Add logging --- tokio-tutorial-mini-redis/Cargo.toml | 4 +++- tokio-tutorial-mini-redis/src/bin/server.rs | 13 +++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/tokio-tutorial-mini-redis/Cargo.toml b/tokio-tutorial-mini-redis/Cargo.toml index 4a82df3..b6caa1b 100644 --- a/tokio-tutorial-mini-redis/Cargo.toml +++ b/tokio-tutorial-mini-redis/Cargo.toml @@ -7,5 +7,7 @@ edition = "2021" [dependencies] bytes = "1" -tokio = { version = "1", features = ["full"] } +env_logger = "0.9" +log = "0.4" mini-redis = "0.4" +tokio = { version = "1", features = ["full"] } diff --git a/tokio-tutorial-mini-redis/src/bin/server.rs b/tokio-tutorial-mini-redis/src/bin/server.rs index 2488f03..441ea18 100644 --- a/tokio-tutorial-mini-redis/src/bin/server.rs +++ b/tokio-tutorial-mini-redis/src/bin/server.rs @@ -8,14 +8,20 @@ use tokio::net::{TcpListener, TcpStream}; type Db = Arc>>; +const LISTEN: &str = "127.0.0.1:6379"; + #[tokio::main] async fn main() { - let listener = TcpListener::bind("127.0.0.1:6379").await.unwrap(); + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init(); + + let listener = TcpListener::bind(LISTEN).await.unwrap(); + log::info!("Listening on {}", LISTEN); let db: Db = Arc::new(Mutex::new(HashMap::new())); loop { // The second item contains the IP and port of the new connection - let (socket, _) = listener.accept().await.unwrap(); + let (socket, addr) = listener.accept().await.unwrap(); + log::debug!("got connection from {:?}", addr); let db_i = db.clone(); tokio::spawn(async move { process(socket, db_i).await }); } @@ -29,12 +35,15 @@ async fn process(socket: TcpStream, db: Db) { Set(cmd) => { // The value is stored as `Vec` db.lock().unwrap().insert(cmd.key().to_string(), cmd.value().clone()); + log::debug!("Set {} → {:?}", &cmd.key(), &cmd.value()); Frame::Simple("OK".to_string()) } Get(cmd) => { if let Some(value) = db.lock().unwrap().get(cmd.key()) { + log::debug!("Get {} → {:?}", &cmd.key(), &value); Frame::Bulk(value.clone()) } else { + log::debug!("Get {} unknown key", &cmd.key()); Frame::Null } } -- 2.39.5