Skip to content

Commit

Permalink
feat: add telementry
Browse files Browse the repository at this point in the history
  • Loading branch information
Devesh Rawat committed Dec 11, 2023
1 parent d2d7bf0 commit 35ca33b
Show file tree
Hide file tree
Showing 10 changed files with 145 additions and 124 deletions.
110 changes: 60 additions & 50 deletions Cargo.lock

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

9 changes: 6 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,17 @@ actix-web = "4.4.0"
chrono = "0.4.31"
config = "0.13.4"
dotenv = "0.15.0"
env_logger = "0.10.1"
log = "0.4.20"
serde = { version = "1.0.193", features = ["derive"] }
sqlx = { version = "0.5.13", features = ["runtime-actix-rustls", "macros", "postgres", "uuid", "chrono", "migrate"] }
sqlx = { version = "0.5.9", features = ["runtime-actix-rustls", "macros", "postgres", "uuid", "chrono", "migrate"] }
tokio = {version ="1.34.0", features = ["macros", "rt-multi-thread"]}
uuid = { version = "0.8.1", features = ["v4"] }
uuid = { version = "0.8.2", features = ["v4"] }
tracing = { version = "0.1.40", features = ["log"] }
tracing-subscriber = { version = "0.3.18", features = ["registry", "env-filter"] }
tracing-bunyan-formatter = "0.3.9"
tracing-log = "0.2.0"
once_cell = "1.18.0"
secrecy = { version = "0.8", features = ["serde"] }


[dev-dependencies]
Expand Down
8 changes: 0 additions & 8 deletions NewsLetter/Cargo.toml

This file was deleted.

14 changes: 0 additions & 14 deletions NewsLetter/src/lib.rs

This file was deleted.

1 change: 0 additions & 1 deletion src/configuration.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
//! src/configuration.rs
#[derive(serde::Deserialize, Debug)]
pub struct Settings {
pub database: DatabaseSettings,
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
pub mod configuration;
pub mod routes;
pub mod startup;
pub mod telemetry;
14 changes: 8 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
//! src/main.rs
#![allow(non_snake_case)]
use dotenv::dotenv;
use env_logger::Env;
use newsLetter::configuration::get_configuration;
use newsLetter::startup::run;
use sqlx::PgPool;
use newsLetter::telemetry;
use sqlx::postgres::PgPool;
use std::net::TcpListener;

#[tokio::main]
async fn main() -> std::io::Result<()> {
dotenv().ok();
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
let subscriber = telemetry::get_subscriber("newsLetter".into(), "info".into(), std::io::stdout);
telemetry::init_subscriber(subscriber);
let configuration = get_configuration().expect("Failed to read configuration.");
let connenction = PgPool::connect(&configuration.database.connection_string())
let connection_pool = PgPool::connect(&configuration.database.connection_string())
.await
.expect("Failed to connect to Postgres.");
let address = format!("127.0.0.1:{}", configuration.application_port);
let listener = TcpListener::bind(&address)?;
run(listener, connenction)?.await
let listener = TcpListener::bind(address)?;
run(listener, connection_pool)?.await?;
Ok(())
}
65 changes: 26 additions & 39 deletions src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use actix_web::{web, HttpResponse};
use chrono::Utc;
use serde::Deserialize;
use sqlx::PgPool;
use tracing::Instrument;
use uuid::Uuid;

#[derive(Deserialize)]
Expand All @@ -13,50 +12,38 @@ pub struct FormData {
pub name: String,
}

#[tracing::instrument(
name = "Adding a new subscriber",
skip(form, pool),
fields(request_id = %Uuid::new_v4(), subscriber_email = %form.email, subscriber_name= %form.name)
)]
pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>) -> 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 '{}' '{}' as a new subscriber.",
request_id,
form.email,
form.name
);
let query_span = tracing::info_span!("Saving new subscriber details in the database");
let res = sqlx::query!(
match insert_subscriber(&pool, &form).await {
Ok(_) => HttpResponse::Ok().finish(),
Err(_) => HttpResponse::InternalServerError().finish(),
}
}

#[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)
INSERT INTO subscriptions (id, email, name, subscribed_at)
VALUES ($1, $2, $3, $4)
"#,
Uuid::new_v4(),
form.email,
form.name,
Utc::now()
)
.execute(pool.get_ref())
.instrument(query_span)
.await;

match res {
Ok(_) => {
tracing::info!(
"request_id {} - New subscriber details have been saved",
request_id
);
HttpResponse::Ok().finish()
}
Err(e) => {
tracing::error!(
"request_id {} - Failed to execute query: {:?}",
request_id,
e
);
HttpResponse::InternalServerError().finish()
}
}
.execute(pool)
.await
.map_err(|e| {
tracing::error!("Failed to execute query: {:?}", e);
e
})?;
Ok(())
}
28 changes: 28 additions & 0 deletions src/telemetry.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//!src/telemetry.rs
use tracing::{subscriber::set_global_default, Subscriber};
use tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer};
use tracing_log::LogTracer;
use tracing_subscriber::fmt::MakeWriter;
use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};

pub fn get_subscriber<Sink>(
name: String,
env_filter: String,
sink: Sink,
) -> impl Subscriber + Sync + Send
where
Sink: for<'a> MakeWriter<'a> + Send + Sync + 'static,
{
let env_filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(env_filter));
let formatting_layer = BunyanFormattingLayer::new(name, sink);
Registry::default()
.with(env_filter)
.with(JsonStorageLayer)
.with(formatting_layer)
}

pub fn init_subscriber(subscriber: impl Subscriber + Send + Sync) {
LogTracer::init().expect("Failed to set logger");
set_global_default(subscriber).expect("Failed to set subscriber");
}
Loading

0 comments on commit 35ca33b

Please sign in to comment.