Changes to allow more dynamic logging

Logs in much greater detail using the tracing packages and formatted using Bunyan. Advised to install bunyan on machine for more pretty logs over raw json.
This commit is contained in:
Nick Bland
2021-11-16 13:50:32 +10:00
parent a746b45f78
commit 1f06f5e66f
8 changed files with 252 additions and 15 deletions
+2 -1
View File
@@ -1,3 +1,4 @@
pub mod configuration;
pub mod routes;
pub mod startup;
pub mod startup;
pub mod telemetry;
+6 -1
View File
@@ -1,10 +1,14 @@
use mail_app::startup::run;
use mail_app::configuration::get_configuration;
use mail_app::telemetry::{get_subscriber, init_subscriber};
use std::net::TcpListener;
use sqlx::PgPool;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let subscriber = get_subscriber("mail_app".into(), "info".into(), std::io::stdout);
init_subscriber(subscriber);
// Attempt to read from config
let configuration = get_configuration().expect("Failed to read configuration data.");
@@ -16,5 +20,6 @@ async fn main() -> std::io::Result<()> {
// Take port from settings file
let address = format!("127.0.0.1:{}", configuration.application_port);
let listener = TcpListener::bind(address)?;
run(listener, connection_pool)?.await
run(listener, connection_pool)?.await?;
Ok(())
}
+29 -9
View File
@@ -2,6 +2,7 @@ use actix_web::{web, HttpResponse};
use sqlx::PgPool;
use chrono::Utc;
use uuid::Uuid;
// use tracing_futures::Instrument;
#[derive(serde::Deserialize)]
pub struct FormData {
@@ -9,10 +10,31 @@ pub struct FormData {
name: String
}
#[allow(clippy::async_yields_async)]
#[tracing::instrument(
name = "Adding a new subscriber",
skip(form, pool),
fields(
subscriber_email = %form.email,
subscriber_name = %form.name
)
)]
pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>,) -> HttpResponse {
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> {
// _connect uses PgPool from the application state as defined in startup.rs
// Use a match statement for the query as it only returns two outcomes
match sqlx::query!(
sqlx::query!(
r#"
INSERT INTO subscriptions (id, email, name, subscribed_at)
VALUES($1, $2, $3, $4)
@@ -22,13 +44,11 @@ pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>,) -> H
form.name,
Utc::now()
)
.execute(pool.as_ref())
.execute(pool)
.await
{
Ok(_) => HttpResponse::Ok().finish(),
Err(e) => {
println!("Failed to execute query: {}", e);
HttpResponse::InternalServerError().finish()
}
}
.map_err(|e| {
tracing::error!("Failed to execute query: {:?}", e);
e
})?;
Ok(())
}
+6 -3
View File
@@ -1,16 +1,19 @@
use actix_web::{web, App, HttpServer};
use actix_web::dev::Server;
use actix_web::web::Data;
use std::net::TcpListener;
use sqlx::PgPool;
use tracing_actix_web::TracingLogger;
use crate::routes;
use crate::routes::{health_check, subscribe};
pub fn run(listener: TcpListener, db_pool: PgPool) -> Result<Server, std::io::Error> {
let db_pool = web::Data::new(db_pool); // Wrap connection in a smart pointer
let server = HttpServer::new(move || {
App::new()
.route("/health_check", web::get().to(routes::health_check))
.route("/subscriptions", web::post().to(routes::subscribe))
.wrap(TracingLogger::default())
.route("/health_check", web::get().to(health_check))
.route("/subscriptions", web::post().to(subscribe))
.app_data(db_pool.clone()) // Get pointer copy and attach to application state
})
.listen(listener)?
+28
View File
@@ -0,0 +1,28 @@
use tracing::{Subscriber, subscriber::set_global_default};
use tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer};
use tracing_log::LogTracer;
use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry, fmt::MakeWriter};
/// Compose multiple layers into a tracing compatible subscriber
pub fn get_subscriber(
name: String,
env_filter: String,
sink: impl MakeWriter + Send + Sync + 'static,
) -> impl Subscriber + Sync + Send {
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)
}
/// Register a subscriber as global default to process span data.
pub fn init_subscriber(subscriber: impl Subscriber + Sync + Send) {
LogTracer::init().expect("Failed to set logger");
set_global_default(subscriber).expect("Failed to set subscriber");
}