Skip to content

Commit

Permalink
Chore: switch to tracing crate for logging
Browse files Browse the repository at this point in the history
  • Loading branch information
cbackas committed Jun 27, 2024
1 parent 0ba7c15 commit 964757b
Show file tree
Hide file tree
Showing 7 changed files with 178 additions and 14 deletions.
147 changes: 147 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ serial_test = "2.0.0"
tokio = { version = "1.28.2", features = ["full"] }
twilight-model = "0.15.2"
warp = "0.3.5"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.16", features = ["env-filter"] }
3 changes: 3 additions & 0 deletions fly.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ primary_region = "ord"
min_machines_running = 0
processes = ["app"]

[env]
RUST_LOG = "hookbuffer=debug"

[checks]
[checks.health]
grace_period = "60s"
Expand Down
8 changes: 4 additions & 4 deletions src/env.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
pub fn get_server_port() -> u16 {
match std::env::var("HOOKBUFFER_PORT") {
Ok(port) => {
println!("[INFO] Found HOOKBUFFER_PORT: {}", port);
tracing::debug!("Found HOOKBUFFER_PORT: {}", port);
match port.parse::<u16>() {
Ok(port) => port,
Err(_) => {
println!("[ERROR] Custom HOOKBUFFER_PORT is not a valid port number, using default port 8000");
tracing::warn!("Custom HOOKBUFFER_PORT is not a valid port number, using default port 8000");
8000
}
}
}
Err(_) => {
println!("[INFO] No HOOKBUFFER_PORT found, using default port 8000");
tracing::debug!("No HOOKBUFFER_PORT found, using default port 8000");
8000
}
}
Expand All @@ -23,7 +23,7 @@ pub fn get_destination_url() -> String {
if !url.ends_with('/') {
url.push('/');
}
println!("[INFO] Found custom HOOKBUFFER_DESTINATION_URL: {}", url);
tracing::info!("Found custom HOOKBUFFER_DESTINATION_URL: {}", url);
url
}
Err(_) => "https://discord.com/".to_string(),
Expand Down
16 changes: 14 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ use std::sync::Arc;

use base64::{engine::general_purpose, Engine as _};
use serde_json::Value;
use tracing::level_filters;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use warp::filters::trace;
use warp::http::HeaderMap;
use warp::path::FullPath;
use warp::reply::{Json, WithStatus};
Expand All @@ -17,6 +21,14 @@ mod structs;

#[tokio::main]
async fn main() {
let env_filter = tracing_subscriber::EnvFilter::builder()
.with_default_directive(level_filters::LevelFilter::INFO.into())
.from_env_lossy();
tracing_subscriber::registry()
.with(env_filter)
.with(tracing_subscriber::fmt::layer())
.init();

// SonarrHandler struct manages the state for the sonarr requests
let sonarr_handler = Arc::new(SonarrHandler::new());

Expand Down Expand Up @@ -59,7 +71,7 @@ async fn main() {

_ => {
// not sonarr, bad request
println!("Received unsupported User-Agent");
tracing::warn!("Received unsupported User-Agent");
warp::reply::with_status(warp::reply::json(&"Received unsupported User-Agent"), warp::http::StatusCode::BAD_REQUEST)
}
}
Expand All @@ -73,7 +85,7 @@ async fn main() {
let routes = health_check.or(catch_all);

let server_port = env::get_server_port();
println!("Server started at localhost:{}", server_port);
tracing::info!("Server started at localhost:{}", server_port);
warp::serve(routes).run(([0, 0, 0, 0], server_port)).await;
}

Expand Down
6 changes: 3 additions & 3 deletions src/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub async fn send_post_request(base_url: String, path: String, payload: DiscordW
loop {
let response = client.post(&full_url).json(&payload).send().await;
if let Err(e) = response {
println!("Failed to send POST request to {}. Error: {:?}, payload: {:?}", full_url, e, payload);
tracing::error!("Failed to send POST request to {}. Error: {:?}, payload: {:?}", full_url, e, payload);
let status: StatusCode = match e.status() {
Some(status) => status,
None => StatusCode::INTERNAL_SERVER_ERROR,
Expand All @@ -29,7 +29,7 @@ pub async fn send_post_request(base_url: String, path: String, payload: DiscordW
if response.status().is_success() {
return Ok(());
} else if response.status() == StatusCode::TOO_MANY_REQUESTS {
println!(
tracing::warn!(
"Rate limited. Retrying in {} seconds. Failed to send POST request to {}. Status: {}, payload: {:?}",
backoff.as_secs(),
full_url,
Expand All @@ -45,7 +45,7 @@ pub async fn send_post_request(base_url: String, path: String, payload: DiscordW
backoff *= 2;
}
} else {
println!(
tracing::error!(
"Failed to send POST request to {}. Status: {}, payload: {:?}",
full_url,
response.status(),
Expand Down
10 changes: 5 additions & 5 deletions src/sonarr_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl SonarrHandler {
}

for episode in &sonarr_request.episodes {
println!(
tracing::info!(
"[Recieved] {:?} Episode: {} - {:02}x{:02}",
sonarr_request.event_type.clone().unwrap(),
sonarr_request.series.title,
Expand All @@ -81,7 +81,7 @@ impl SonarrHandler {
timer_state.timer_end = timer_end;
} else {
// if there isn't a TimerState, create one with this request in the queue and a new timer_end Instant
println!("[Timer] new timer started for {}", request_path);
tracing::info!("[Timer] new timer started for {}", request_path);
let timer_state = TimerState {
queue: vec![sonarr_request],
timer_end,
Expand Down Expand Up @@ -140,7 +140,7 @@ async fn process_timer(
// only proceed if the timer ID hasn't changed
// this is how we know the timer hasn't been reset since this function was spawned
if timer_state.timer_id == timer_id {
println!(
tracing::info!(
"[Timer] timer expired for {} with {} requests in queue",
request_path,
timer_state.queue.len()
Expand Down Expand Up @@ -173,10 +173,10 @@ async fn process_timer(

match send_post_request(destination_url.to_string(), request_path.to_string(), webhook).await {
Ok(_) => {
println!("[Forwarded] {:?} sent to discord succesfully successfully", group_key);
tracing::info!("[Forwarded] {:?} sent to discord succesfully successfully", group_key);
}
Err(e) => {
eprintln!("Failed to send POST request: {:?}", e);
tracing::error!("Failed to send POST request: {:?}", e);
}
}

Expand Down

0 comments on commit 964757b

Please sign in to comment.