Skip to content

Commit

Permalink
feat: add logger
Browse files Browse the repository at this point in the history
  • Loading branch information
Yag000 committed Aug 29, 2023
1 parent 0c6d7e0 commit a76eddc
Show file tree
Hide file tree
Showing 6 changed files with 175 additions and 6 deletions.
145 changes: 142 additions & 3 deletions Cargo.lock

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

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ config = { version = "0.13", default-features = false, features = ["yaml"] }
sqlx = { version = "0.6", default-features = false, features = ["runtime-actix-rustls", "macros", "postgres", "uuid", "chrono", "migrate"] }
uuid = { version = "1", features = ["v4"] }
chrono = { version = "0.4.22", default-features = false, features = ["clock"] }
tracing = { version = "0.1", features = ["log"] }
tracing-subscriber = { version = "0.3", features = ["registry", "env-filter"] }
tracing-bunyan-formatter = "0.3"
tracing-log = "0.1"

[dev-dependencies]
reqwest = { version = "0.11", features = ["json"] }
14 changes: 14 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
use sqlx::PgPool;
use std::net::TcpListener;
use tracing::subscriber::set_global_default;
use tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer};
use tracing_log::LogTracer;
use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
use zero2prod::{configurations::get_configuration, startup::run};

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
// Logger setup
LogTracer::init().expect("Failed to set logger");
// Info or above will be logged if the RUST_LOG environment variable is not set
let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
let foirmatting_layer = BunyanFormattingLayer::new("zero2prod".into(), std::io::stdout);
let subscriber = Registry::default()
.with(env_filter)
.with(JsonStorageLayer)
.with(foirmatting_layer);
set_global_default(subscriber).expect("Failed to set subscriber");
// We want to panic if we cannot read the configuration
let configuration = get_configuration().expect("Failed to read configurations");
let connection = PgPool::connect(&configuration.database.get_connnection_string())
Expand Down
14 changes: 13 additions & 1 deletion src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use actix_web::{web, HttpResponse};
use chrono::Utc;
use sqlx::PgPool;
use tracing::Instrument;
use uuid::Uuid;

#[allow(dead_code)]
Expand All @@ -11,6 +12,16 @@ pub struct FormData {
}

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();

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)
Expand All @@ -24,11 +35,12 @@ pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>) -> Ht
// We use `get_ref` to get an immutable reference to the `PgConnection`
// wrapped by `web::Data`.
.execute(pool.get_ref())
.instrument(query_span)
.await
{
Ok(_) => HttpResponse::Ok().finish(),
Err(e) => {
eprintln!("Failed to execute query: {}", e);
tracing::error!("Failed to execute query: {:?}", e);
HttpResponse::InternalServerError().finish()
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/startup.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::net::TcpListener;

use actix_web::{dev::Server, web, App, HttpServer};
use actix_web::{dev::Server, middleware::Logger, web, App, HttpServer};
use sqlx::PgPool;

use crate::routes::{health_check, subscribe};
Expand All @@ -9,6 +9,7 @@ pub fn run(listener: TcpListener, db_pool: PgPool) -> Result<Server, std::io::Er
let connection = web::Data::new(db_pool);
let server = HttpServer::new(move || {
App::new()
.wrap(Logger::default())
.route("/health_check", web::get().to(health_check))
.route("/subscriptions", web::post().to(subscribe))
.app_data(connection.clone())
Expand Down
1 change: 0 additions & 1 deletion tests/health_check.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use actix_web::dev::ConnectionInfo;
use sqlx::{Connection, Executor, PgConnection, PgPool};
use std::net::TcpListener;
use uuid::Uuid;
Expand Down

0 comments on commit a76eddc

Please sign in to comment.