feat(log): database operations and API logs split
This commit is contained in:
parent
9336235b64
commit
3a0576ba48
@ -1,7 +1,6 @@
|
||||
use actix_web::{web, HttpResponse};
|
||||
use chrono::Utc;
|
||||
use sqlx::PgPool;
|
||||
use tracing::Instrument;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
@ -10,45 +9,49 @@ pub struct FormData {
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
name = "Adding a new subscriber",
|
||||
// functions args isn't really relevant to the span
|
||||
skip(form, db_conn_pool),
|
||||
fields(
|
||||
request_id = %Uuid::new_v4(),
|
||||
subscriber_email = %form.email,
|
||||
subscriber_name = %form.name
|
||||
)
|
||||
)]
|
||||
pub async fn subscribe_route(
|
||||
form: web::Form<FormData>,
|
||||
db_conn_pool: web::Data<PgPool>,
|
||||
) -> HttpResponse {
|
||||
let request_id = Uuid::new_v4();
|
||||
match insert_subscriber(&db_conn_pool, &form).await {
|
||||
Ok(_) => HttpResponse::Ok().finish(),
|
||||
Err(_) => HttpResponse::InternalServerError().finish(),
|
||||
}
|
||||
}
|
||||
|
||||
let request_span = tracing::info_span!(
|
||||
"Adding new subscriber",
|
||||
%request_id,
|
||||
subscriber_email = %form.email,
|
||||
subscriber_name = %form.name
|
||||
);
|
||||
|
||||
let _request_span_guard = request_span.enter();
|
||||
|
||||
let query_span = tracing::info_span!("Adding new subscriber in PostgreSQL");
|
||||
|
||||
match sqlx::query!(
|
||||
#[tracing::instrument(
|
||||
name = "Saving new subscriber details in the database",
|
||||
skip(form, pool)
|
||||
)]
|
||||
pub async fn insert_subscriber(pool: &PgPool, form: &FormData) -> Result<(), sqlx::Error> {
|
||||
sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO subscriptions (id, email, name, subscribed_at)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
"#,
|
||||
"#,
|
||||
Uuid::new_v4(),
|
||||
form.email,
|
||||
form.name,
|
||||
Utc::now()
|
||||
)
|
||||
.execute(db_conn_pool.get_ref())
|
||||
.instrument(query_span)
|
||||
.execute(pool)
|
||||
.await
|
||||
{
|
||||
Ok(_) => HttpResponse::Ok().finish(),
|
||||
Err(err) => {
|
||||
tracing::error!(
|
||||
"request_id {} - Failed to execute query: {:?}",
|
||||
request_id,
|
||||
err
|
||||
);
|
||||
HttpResponse::InternalServerError().finish()
|
||||
}
|
||||
}
|
||||
.map_err(|e| {
|
||||
tracing::error!("Failed to execute query: {:?}", e);
|
||||
e
|
||||
// Using the `?` operator to return early
|
||||
// if the function failed, returning a sqlx::Error
|
||||
// We will talk about error handling in depth later!
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user