Skip to content

Commit

Permalink
feat: 第四章功能代码,增加tracing
Browse files Browse the repository at this point in the history
  • Loading branch information
fan-tastic-z committed Oct 25, 2024
1 parent 8a290e8 commit 2761cc1
Show file tree
Hide file tree
Showing 9 changed files with 443 additions and 4 deletions.
389 changes: 389 additions & 0 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ path = "src/main.rs"
name = "zero2prod"

[dependencies]
axum = { version = "0.7.7", features = ["macros"] }
axum = { version = "0.7.7", features = ["macros", "tracing"] }
chrono = { version = "0.4.38", features = ["serde"] }
config = "0.14.1"
serde = { version = "1.0.213", features = ["derive"] }
Expand All @@ -26,7 +26,12 @@ sqlx = { version = "0.8.2", features = [
] }
tokio = { version = "1.41.0", features = ["rt-multi-thread", "macros"] }
tower = "0.5.1"
tower-http = { version = "0.6.1", features = ["compression-full", "trace"] }
tracing = "0.1.40"
tracing-appender = "0.2.3"
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "json"] }
uuid = { version = "1.11.0", features = ["v4"] }

[dev-dependencies]
mime = "0.3.17"
once_cell = "1.20.2"
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod configuration;
pub mod routes;
pub mod startup;
pub mod telemetry;
5 changes: 4 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use std::sync::Arc;

use sqlx::postgres::PgPoolOptions;
use zero2prod::{configuration::get_configuration, startup::run};

use zero2prod::{configuration::get_configuration, startup::run, telemetry::init_tracing};

#[tokio::main]
async fn main() -> std::io::Result<()> {
init_tracing();

let configuration = get_configuration().expect("Failed to read configuration.");
let connection_string = configuration.database.connection_string();

Expand Down
8 changes: 6 additions & 2 deletions src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use axum::{
};
use chrono::Utc;
use serde::Deserialize;
use tracing::{error, info};
use uuid::Uuid;

use crate::startup::AppState;
Expand Down Expand Up @@ -34,9 +35,12 @@ pub async fn subscribe(
.execute(state.db_pool.as_ref())
.await;
match res {
Ok(_) => Ok((StatusCode::OK).into_response()),
Ok(_) => {
info!("New subscriber detail have been saved");
Ok((StatusCode::OK).into_response())
}
Err(e) => {
println!("Failed to execute query: {}", e);
error!("Failed to execute query: {}", e);
Err(StatusCode::INTERNAL_SERVER_ERROR)
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use sqlx::{
Executor, PgPool, Pool, Postgres,
};
use tokio::net::TcpListener;
use tower_http::trace::TraceLayer;

use crate::{
configuration::DatabaseSettings,
Expand All @@ -25,6 +26,7 @@ pub fn app(state: AppState) -> Router {
.route("/health", get(health))
.route("/subscriptions", post(subscribe))
.with_state(state)
.layer(TraceLayer::new_for_http())
}

pub async fn run(listener: TcpListener, db_pool: Arc<Pool<Postgres>>) -> std::io::Result<()> {
Expand Down
28 changes: 28 additions & 0 deletions src/telemetry.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use tracing::level_filters::LevelFilter;
use tracing_subscriber::{
fmt::{self, format::FmtSpan},
layer::SubscriberExt,
util::SubscriberInitExt,
Layer,
};

pub fn init_tracing() {
// console layer for tracing-subscriber
let console = fmt::Layer::new()
.with_span_events(FmtSpan::CLOSE)
.json()
.with_filter(LevelFilter::DEBUG);

// file appender layer for tracing-subscriber
let file_appender = tracing_appender::rolling::daily("./", "zero2prod.log");
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
let file = fmt::Layer::new()
.with_writer(non_blocking)
.json()
.with_filter(LevelFilter::DEBUG);

tracing_subscriber::registry()
.with(console)
.with(file)
.init();
}
7 changes: 7 additions & 0 deletions tests/health_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,20 @@ use axum::{
http::{self, header::CONTENT_LENGTH, HeaderValue, Request},
};

use once_cell::sync::Lazy;
use sqlx::PgPool;
use tower::ServiceExt;
use uuid::Uuid;
use zero2prod::{
configuration::get_configuration,
startup::{app, configuration_database, AppState},
telemetry::init_tracing,
};

static TRACING: Lazy<()> = Lazy::new(|| {
init_tracing();
});

#[tokio::test]
async fn health_check_works() {
let db_pool = Arc::new(spawn_app().await);
Expand Down Expand Up @@ -113,6 +119,7 @@ async fn subscribe_returns_a_422_when_data_is_missing() {
}

async fn spawn_app() -> PgPool {
Lazy::force(&TRACING);
let mut configuration = get_configuration().expect("Failed to read configuration.");
configuration.database.database_name = Uuid::new_v4().to_string();
configuration_database(&configuration.database).await
Expand Down
Empty file added zero2prod.log.2024-10-25
Empty file.

0 comments on commit 2761cc1

Please sign in to comment.