From ef08b9e83856af515bfd15b77e3e82550f3df1d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Orhun=20Parmaks=C4=B1z?= Date: Tue, 5 Dec 2023 15:12:02 +0300 Subject: [PATCH] refactor(tracing): use macros from tracing crate --- src/auth.rs | 4 ++-- src/config.rs | 8 ++++---- src/lib.rs | 4 ++++ src/main.rs | 24 ++++++++++++++---------- src/middleware.rs | 5 ++--- src/server.rs | 18 +++++++++--------- 6 files changed, 35 insertions(+), 28 deletions(-) diff --git a/src/auth.rs b/src/auth.rs index 3ece6cf..7ebf142 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -12,12 +12,12 @@ pub fn check(host: &str, headers: &HeaderMap, tokens: Option>) -> Re .map(|v| v.split_whitespace().last().unwrap_or_default()); if !tokens.iter().any(|v| v == auth_header.unwrap_or_default()) { #[cfg(debug_assertions)] - tracing::warn!( + warn!( "authorization failure for {host} (token: {})", auth_header.unwrap_or("none"), ); #[cfg(not(debug_assertions))] - tracing::warn!("authorization failure for {host}"); + warn!("authorization failure for {host}"); return Err(error::ErrorUnauthorized("unauthorized\n")); } } diff --git a/src/config.rs b/src/config.rs index 1edd93b..7ddc37c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -177,19 +177,19 @@ impl Config { #[allow(deprecated)] pub fn warn_deprecation(&self) { if self.server.auth_token.is_some() { - tracing::warn!("[server].auth_token is deprecated, please use [server].auth_tokens"); + warn!("[server].auth_token is deprecated, please use [server].auth_tokens"); } if self.server.landing_page.is_some() { - tracing::warn!("[server].landing_page is deprecated, please use [landing_page].text"); + warn!("[server].landing_page is deprecated, please use [landing_page].text"); } if self.server.landing_page_content_type.is_some() { - tracing::warn!( + warn!( "[server].landing_page_content_type is deprecated, please use [landing_page].content_type" ); } if let Some(random_url) = &self.paste.random_url { if random_url.enabled.is_some() { - tracing::warn!( + warn!( "[paste].random_url.enabled is deprecated, disable it by commenting out [paste].random_url" ); } diff --git a/src/lib.rs b/src/lib.rs index 035f398..731ad8b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,6 +31,10 @@ pub mod util; /// Custom middleware implementation. pub mod middleware; +// Use macros from tracing crate. +#[macro_use] +extern crate tracing; + /// Environment variable for setting the configuration file path. pub const CONFIG_ENV: &str = "CONFIG"; diff --git a/src/main.rs b/src/main.rs index 3b1fe1c..c38911c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -28,6 +28,10 @@ use { shuttle_actix_web::ShuttleActixWeb, }; +// Use macros from tracing crate. +#[macro_use] +extern crate tracing; + /// Sets up the application. /// /// * loads the configuration @@ -58,7 +62,7 @@ fn setup(config_folder: &Path) -> IoResult<(Data>, ServerConfig, None => config_folder.join("config.toml"), }; let config = Config::parse(&config_path).expect("failed to parse config"); - tracing::trace!("{:#?}", config); + trace!("{:#?}", config); config.warn_deprecation(); let server_config = config.server.clone(); let paste_config = RwLock::new(config.paste.clone()); @@ -91,18 +95,18 @@ fn setup(config_folder: &Path) -> IoResult<(Data>, ServerConfig, Ok(config) => match cloned_config.write() { Ok(mut cloned_config) => { *cloned_config = config.clone(); - tracing::info!("Configuration has been updated."); + info!("Configuration has been updated."); if let Err(e) = config_sender.send(config) { - tracing::error!("Failed to send config for the cleanup routine: {}", e) + error!("Failed to send config for the cleanup routine: {}", e) } cloned_config.warn_deprecation(); } Err(e) => { - tracing::error!("Failed to acquire config: {}", e); + error!("Failed to acquire config: {}", e); } }, Err(e) => { - tracing::error!("Failed to update config: {}", e); + error!("Failed to update config: {}", e); } } } @@ -121,11 +125,11 @@ fn setup(config_folder: &Path) -> IoResult<(Data>, ServerConfig, .and_then(|v| v.delete_expired_files.clone()) { if cleanup_config.enabled { - tracing::debug!("Running cleanup..."); + debug!("Running cleanup..."); for file in util::get_expired_files(&upload_path) { match fs::remove_file(&file) { - Ok(()) => tracing::info!("Removed expired file: {:?}", file), - Err(e) => tracing::error!("Cannot remove expired file: {}", e), + Ok(()) => info!("Removed expired file: {:?}", file), + Err(e) => error!("Cannot remove expired file: {}", e), } } thread::sleep(cleanup_config.interval); @@ -142,7 +146,7 @@ fn setup(config_folder: &Path) -> IoResult<(Data>, ServerConfig, *paste_config = new_config.paste; } Err(e) => { - tracing::error!("Failed to update config for the cleanup routine: {}", e); + error!("Failed to update config for the cleanup routine: {}", e); } } } @@ -184,7 +188,7 @@ async fn main() -> IoResult<()> { } // Run the server. - tracing::info!("Server is running at {}", server_config.address); + info!("Server is running at {}", server_config.address); http_server.run().await } diff --git a/src/middleware.rs b/src/middleware.rs index 4a00ccc..0c647a8 100644 --- a/src/middleware.rs +++ b/src/middleware.rs @@ -70,10 +70,9 @@ where .and_then(|v| v.parse::().ok()) { if content_length > self.max_bytes { - tracing::warn!( + warn!( "Upload rejected due to exceeded limit. ({:-#} > {:-#})", - content_length, - self.max_bytes + content_length, self.max_bytes ); return Box::pin(async move { // drain the body due to https://github.com/actix/actix-web/issues/2695 diff --git a/src/server.rs b/src/server.rs index 0b13857..d2f752e 100644 --- a/src/server.rs +++ b/src/server.rs @@ -162,7 +162,7 @@ async fn delete( let host = connection.realip_remote_addr().unwrap_or("unknown host"); let tokens = config.get_tokens(TokenType::Delete); if tokens.is_none() { - tracing::warn!("delete endpoint is not served because there are no delete_tokens set"); + warn!("delete endpoint is not served because there are no delete_tokens set"); return Err(error::ErrorForbidden("endpoint is not exposed\n")); } auth::check(host, request.headers(), tokens)?; @@ -170,9 +170,9 @@ async fn delete( return Err(error::ErrorNotFound("file is not found or expired :(\n")); } match fs::remove_file(path) { - Ok(_) => tracing::info!("deleted file: {:?}", file), + Ok(_) => info!("deleted file: {:?}", file), Err(e) => { - tracing::error!("cannot delete file: {}", e); + error!("cannot delete file: {}", e); return Err(error::ErrorInternalServerError("cannot delete file")); } } @@ -193,7 +193,7 @@ async fn version( let tokens = config.get_tokens(TokenType::Auth); auth::check(host, request.headers(), tokens)?; if !config.server.expose_version.unwrap_or(false) { - tracing::warn!("server is not configured to expose version endpoint"); + warn!("server is not configured to expose version endpoint"); Err(error::ErrorForbidden("endpoint is not exposed\n"))?; } let version = env!("CARGO_PKG_VERSION"); @@ -249,7 +249,7 @@ async fn upload( bytes.append(&mut chunk?.to_vec()); } if bytes.is_empty() { - tracing::warn!("{} sent zero bytes", host); + warn!("{} sent zero bytes", host); return Err(error::ErrorBadRequest("invalid file size")); } if paste_type != PasteType::Oneshot @@ -304,7 +304,7 @@ async fn upload( paste.store_url(expiry_date, &config)? } }; - tracing::info!( + info!( "{} ({}) is uploaded from {}", file_name, Byte::from_u128(paste.data.len() as u128) @@ -320,7 +320,7 @@ async fn upload( } urls.push(format!("{}/{}\n", server_url, file_name)); } else { - tracing::warn!("{} sent an invalid form field", host); + warn!("{} sent an invalid form field", host); return Err(error::ErrorBadRequest("invalid form field")); } } @@ -353,7 +353,7 @@ async fn list( let tokens = config.get_tokens(TokenType::Auth); auth::check(host, request.headers(), tokens)?; if !config.server.expose_list.unwrap_or(false) { - tracing::warn!("server is not configured to expose list endpoint"); + warn!("server is not configured to expose list endpoint"); Err(error::ErrorForbidden("endpoint is not exposed\n"))?; } let entries: Vec = fs::read_dir(config.server.upload_path)? @@ -367,7 +367,7 @@ async fn list( metadata } Err(e) => { - tracing::error!("failed to read metadata: {e}"); + error!("failed to read metadata: {e}"); return None; } };