refactor(tracing): use macros from tracing crate

This commit is contained in:
Orhun Parmaksız 2023-12-05 15:12:02 +03:00
parent a291307bec
commit ef08b9e838
No known key found for this signature in database
GPG Key ID: F83424824B3E4B90
6 changed files with 35 additions and 28 deletions

View File

@ -12,12 +12,12 @@ pub fn check(host: &str, headers: &HeaderMap, tokens: Option<Vec<String>>) -> Re
.map(|v| v.split_whitespace().last().unwrap_or_default()); .map(|v| v.split_whitespace().last().unwrap_or_default());
if !tokens.iter().any(|v| v == auth_header.unwrap_or_default()) { if !tokens.iter().any(|v| v == auth_header.unwrap_or_default()) {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
tracing::warn!( warn!(
"authorization failure for {host} (token: {})", "authorization failure for {host} (token: {})",
auth_header.unwrap_or("none"), auth_header.unwrap_or("none"),
); );
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
tracing::warn!("authorization failure for {host}"); warn!("authorization failure for {host}");
return Err(error::ErrorUnauthorized("unauthorized\n")); return Err(error::ErrorUnauthorized("unauthorized\n"));
} }
} }

View File

@ -177,19 +177,19 @@ impl Config {
#[allow(deprecated)] #[allow(deprecated)]
pub fn warn_deprecation(&self) { pub fn warn_deprecation(&self) {
if self.server.auth_token.is_some() { 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() { 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() { 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" "[server].landing_page_content_type is deprecated, please use [landing_page].content_type"
); );
} }
if let Some(random_url) = &self.paste.random_url { if let Some(random_url) = &self.paste.random_url {
if random_url.enabled.is_some() { if random_url.enabled.is_some() {
tracing::warn!( warn!(
"[paste].random_url.enabled is deprecated, disable it by commenting out [paste].random_url" "[paste].random_url.enabled is deprecated, disable it by commenting out [paste].random_url"
); );
} }

View File

@ -31,6 +31,10 @@ pub mod util;
/// Custom middleware implementation. /// Custom middleware implementation.
pub mod middleware; pub mod middleware;
// Use macros from tracing crate.
#[macro_use]
extern crate tracing;
/// Environment variable for setting the configuration file path. /// Environment variable for setting the configuration file path.
pub const CONFIG_ENV: &str = "CONFIG"; pub const CONFIG_ENV: &str = "CONFIG";

View File

@ -28,6 +28,10 @@ use {
shuttle_actix_web::ShuttleActixWeb, shuttle_actix_web::ShuttleActixWeb,
}; };
// Use macros from tracing crate.
#[macro_use]
extern crate tracing;
/// Sets up the application. /// Sets up the application.
/// ///
/// * loads the configuration /// * loads the configuration
@ -58,7 +62,7 @@ fn setup(config_folder: &Path) -> IoResult<(Data<RwLock<Config>>, ServerConfig,
None => config_folder.join("config.toml"), None => config_folder.join("config.toml"),
}; };
let config = Config::parse(&config_path).expect("failed to parse config"); let config = Config::parse(&config_path).expect("failed to parse config");
tracing::trace!("{:#?}", config); trace!("{:#?}", config);
config.warn_deprecation(); config.warn_deprecation();
let server_config = config.server.clone(); let server_config = config.server.clone();
let paste_config = RwLock::new(config.paste.clone()); let paste_config = RwLock::new(config.paste.clone());
@ -91,18 +95,18 @@ fn setup(config_folder: &Path) -> IoResult<(Data<RwLock<Config>>, ServerConfig,
Ok(config) => match cloned_config.write() { Ok(config) => match cloned_config.write() {
Ok(mut cloned_config) => { Ok(mut cloned_config) => {
*cloned_config = config.clone(); *cloned_config = config.clone();
tracing::info!("Configuration has been updated."); info!("Configuration has been updated.");
if let Err(e) = config_sender.send(config) { 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(); cloned_config.warn_deprecation();
} }
Err(e) => { Err(e) => {
tracing::error!("Failed to acquire config: {}", e); error!("Failed to acquire config: {}", e);
} }
}, },
Err(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<RwLock<Config>>, ServerConfig,
.and_then(|v| v.delete_expired_files.clone()) .and_then(|v| v.delete_expired_files.clone())
{ {
if cleanup_config.enabled { if cleanup_config.enabled {
tracing::debug!("Running cleanup..."); debug!("Running cleanup...");
for file in util::get_expired_files(&upload_path) { for file in util::get_expired_files(&upload_path) {
match fs::remove_file(&file) { match fs::remove_file(&file) {
Ok(()) => tracing::info!("Removed expired file: {:?}", file), Ok(()) => info!("Removed expired file: {:?}", file),
Err(e) => tracing::error!("Cannot remove expired file: {}", e), Err(e) => error!("Cannot remove expired file: {}", e),
} }
} }
thread::sleep(cleanup_config.interval); thread::sleep(cleanup_config.interval);
@ -142,7 +146,7 @@ fn setup(config_folder: &Path) -> IoResult<(Data<RwLock<Config>>, ServerConfig,
*paste_config = new_config.paste; *paste_config = new_config.paste;
} }
Err(e) => { 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. // Run the server.
tracing::info!("Server is running at {}", server_config.address); info!("Server is running at {}", server_config.address);
http_server.run().await http_server.run().await
} }

View File

@ -70,10 +70,9 @@ where
.and_then(|v| v.parse::<Byte>().ok()) .and_then(|v| v.parse::<Byte>().ok())
{ {
if content_length > self.max_bytes { if content_length > self.max_bytes {
tracing::warn!( warn!(
"Upload rejected due to exceeded limit. ({:-#} > {:-#})", "Upload rejected due to exceeded limit. ({:-#} > {:-#})",
content_length, content_length, self.max_bytes
self.max_bytes
); );
return Box::pin(async move { return Box::pin(async move {
// drain the body due to https://github.com/actix/actix-web/issues/2695 // drain the body due to https://github.com/actix/actix-web/issues/2695

View File

@ -162,7 +162,7 @@ async fn delete(
let host = connection.realip_remote_addr().unwrap_or("unknown host"); let host = connection.realip_remote_addr().unwrap_or("unknown host");
let tokens = config.get_tokens(TokenType::Delete); let tokens = config.get_tokens(TokenType::Delete);
if tokens.is_none() { 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")); return Err(error::ErrorForbidden("endpoint is not exposed\n"));
} }
auth::check(host, request.headers(), tokens)?; auth::check(host, request.headers(), tokens)?;
@ -170,9 +170,9 @@ async fn delete(
return Err(error::ErrorNotFound("file is not found or expired :(\n")); return Err(error::ErrorNotFound("file is not found or expired :(\n"));
} }
match fs::remove_file(path) { match fs::remove_file(path) {
Ok(_) => tracing::info!("deleted file: {:?}", file), Ok(_) => info!("deleted file: {:?}", file),
Err(e) => { Err(e) => {
tracing::error!("cannot delete file: {}", e); error!("cannot delete file: {}", e);
return Err(error::ErrorInternalServerError("cannot delete file")); return Err(error::ErrorInternalServerError("cannot delete file"));
} }
} }
@ -193,7 +193,7 @@ async fn version(
let tokens = config.get_tokens(TokenType::Auth); let tokens = config.get_tokens(TokenType::Auth);
auth::check(host, request.headers(), tokens)?; auth::check(host, request.headers(), tokens)?;
if !config.server.expose_version.unwrap_or(false) { 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"))?; Err(error::ErrorForbidden("endpoint is not exposed\n"))?;
} }
let version = env!("CARGO_PKG_VERSION"); let version = env!("CARGO_PKG_VERSION");
@ -249,7 +249,7 @@ async fn upload(
bytes.append(&mut chunk?.to_vec()); bytes.append(&mut chunk?.to_vec());
} }
if bytes.is_empty() { if bytes.is_empty() {
tracing::warn!("{} sent zero bytes", host); warn!("{} sent zero bytes", host);
return Err(error::ErrorBadRequest("invalid file size")); return Err(error::ErrorBadRequest("invalid file size"));
} }
if paste_type != PasteType::Oneshot if paste_type != PasteType::Oneshot
@ -304,7 +304,7 @@ async fn upload(
paste.store_url(expiry_date, &config)? paste.store_url(expiry_date, &config)?
} }
}; };
tracing::info!( info!(
"{} ({}) is uploaded from {}", "{} ({}) is uploaded from {}",
file_name, file_name,
Byte::from_u128(paste.data.len() as u128) Byte::from_u128(paste.data.len() as u128)
@ -320,7 +320,7 @@ async fn upload(
} }
urls.push(format!("{}/{}\n", server_url, file_name)); urls.push(format!("{}/{}\n", server_url, file_name));
} else { } else {
tracing::warn!("{} sent an invalid form field", host); warn!("{} sent an invalid form field", host);
return Err(error::ErrorBadRequest("invalid form field")); return Err(error::ErrorBadRequest("invalid form field"));
} }
} }
@ -353,7 +353,7 @@ async fn list(
let tokens = config.get_tokens(TokenType::Auth); let tokens = config.get_tokens(TokenType::Auth);
auth::check(host, request.headers(), tokens)?; auth::check(host, request.headers(), tokens)?;
if !config.server.expose_list.unwrap_or(false) { 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"))?; Err(error::ErrorForbidden("endpoint is not exposed\n"))?;
} }
let entries: Vec<ListItem> = fs::read_dir(config.server.upload_path)? let entries: Vec<ListItem> = fs::read_dir(config.server.upload_path)?
@ -367,7 +367,7 @@ async fn list(
metadata metadata
} }
Err(e) => { Err(e) => {
tracing::error!("failed to read metadata: {e}"); error!("failed to read metadata: {e}");
return None; return None;
} }
}; };