diff --git a/Cargo.toml b/Cargo.toml index 67a844b..be9c48a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,9 @@ config = "0.14.0" uuid = { version="1.10.0", features = ["v4"] } chrono = { version = "0.4.19", default-features = false, features = ["clock"] } serde_json = "1.0.128" +env_logger = "0.11.5" +log = "0.4.22" +tracing = { version = "0.1.40", features = ["log"] } [dev-dependencies] reqwest = { version = "0.12.7", features = ["json"] } diff --git a/src/main.rs b/src/main.rs index cad5014..a2d5e7a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,11 +2,12 @@ use std::net::TcpListener; use isotopes::configuration::get_configuration; use sqlx::PgPool; use isotopes::startup::run; +use env_logger::Env; #[tokio::main] async fn main() -> Result<(), std::io::Error> { // let address = "127.0.0.1:4000"; - + env_logger::Builder::from_env(Env::default().default_filter_or("info")).init(); let configuration = get_configuration() .expect("Failed to read configuration."); diff --git a/src/routes/subscriptions.rs b/src/routes/subscriptions.rs index 4daad11..3944b4d 100644 --- a/src/routes/subscriptions.rs +++ b/src/routes/subscriptions.rs @@ -1,6 +1,7 @@ use actix_web::{web, HttpResponse}; use sqlx::{ PgPool}; use chrono::Utc; +use tracing::Instrument; use uuid::Uuid; #[derive(serde::Deserialize)] @@ -12,6 +13,21 @@ pub async fn subscribe( form: web::Form, pool: web::Data ) -> HttpResponse { + + let request_id = Uuid::new_v4(); + + let request_span = tracing::info_span!( + "Adding a new subscriber", + %request_id, + subscriber_email = %form.email, + subscriber_name = %form.name + ); + + let _request_span_guard = request_span.enter(); + + tracing::info!("request_id {} - Adding new subscriber: {} - {}", + request_id, form.email, form.name); + let query_span = tracing::info_span!("Saving new subscriber details in the database"); match sqlx::query!( r#" INSERT INTO subscriptions (id, email, name, subscribed_at) @@ -21,11 +37,14 @@ pub async fn subscribe( form.email, form.name, Utc::now() - ).execute(pool.get_ref()).await { - Ok(_) => HttpResponse::Ok().finish(), + ).execute(pool.get_ref()) + .instrument(query_span) + .await { + Ok(_) => { + tracing::info!("request_id {} - New subscriber added: {} - {}", request_id, form.email, form.name); + HttpResponse::Ok().finish()}, Err(e) => { - - println!("Failed to execute query: {}", e); + tracing::error!("request_id {} - Failed to execute query: {:?}", request_id, e); HttpResponse::InternalServerError().finish() } diff --git a/src/startup.rs b/src/startup.rs index b863471..20a62dc 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -1,6 +1,7 @@ use crate::routes::{health_check, subscribe}; use actix_web::dev::Server; use actix_web::{web, App, HttpServer}; +use actix_web::middleware::Logger; use sqlx::PgPool; @@ -12,6 +13,7 @@ pub fn run(listener: TcpListener, db_pool: PgPool) -> Result