Skip to content

Commit

Permalink
refactor(tracing): use macros from tracing crate
Browse files Browse the repository at this point in the history
  • Loading branch information
orhun committed Dec 5, 2023
1 parent a291307 commit ef08b9e
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 28 deletions.
4 changes: 2 additions & 2 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
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"));
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
);
}
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down
24 changes: 14 additions & 10 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -58,7 +62,7 @@ fn setup(config_folder: &Path) -> IoResult<(Data<RwLock<Config>>, 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());
Expand Down Expand Up @@ -91,18 +95,18 @@ fn setup(config_folder: &Path) -> IoResult<(Data<RwLock<Config>>, 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);
}
}
}
Expand All @@ -121,11 +125,11 @@ fn setup(config_folder: &Path) -> IoResult<(Data<RwLock<Config>>, 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);
Expand All @@ -142,7 +146,7 @@ fn setup(config_folder: &Path) -> IoResult<(Data<RwLock<Config>>, 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);
}
}
}
Expand Down Expand Up @@ -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
}

Expand Down
5 changes: 2 additions & 3 deletions src/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,9 @@ where
.and_then(|v| v.parse::<Byte>().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
Expand Down
18 changes: 9 additions & 9 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,17 +162,17 @@ 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)?;
if !path.is_file() || !path.exists() {
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"));
}
}
Expand All @@ -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");
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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"));
}
}
Expand Down Expand Up @@ -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<ListItem> = fs::read_dir(config.server.upload_path)?
Expand All @@ -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;
}
};
Expand Down

0 comments on commit ef08b9e

Please sign in to comment.