feat: add tracing

This commit is contained in:
Sandro Eiler 2024-02-04 13:48:31 +01:00
parent 653502c470
commit 93140e7d22
8 changed files with 431 additions and 174 deletions

View file

@ -1,8 +1,27 @@
use learn_axum::configuration::{get_configuration, DatabaseSettings};
use learn_axum::telemetry::{get_subscriber, init_subscriber};
use once_cell::sync::Lazy;
use sqlx::{Connection, Executor, PgConnection, PgPool};
use tokio::net::TcpListener;
use uuid::Uuid;
/// Ensure that the `tracing` stack is only initialised once using `once_cell`
static TRACING: Lazy<()> = Lazy::new(|| {
let default_filter_level = "info".to_string();
let subscriber_name = "test".to_string();
// We cannot assign the output of `get_subscriber` to a variable based on the
// value TEST_LOG` because the sink is part of the type returned by
// `get_subscriber`, therefore they are not the same type. We could work around
// it, but this is the most straight-forward way of moving forward.
if std::env::var("TEST_LOG").is_ok() {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::stdout);
init_subscriber(subscriber);
} else {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::sink);
init_subscriber(subscriber);
};
});
pub struct TestApp {
pub address: String,
pub db_pool: PgPool,
@ -86,6 +105,10 @@ async fn subscribe_returns_a_200_for_valid_form_data() {
}
async fn spawn_app() -> TestApp {
// The first time `initialize` is invoked the code in `TRACING` is executed.
// All other invocations will instead skip execution.
Lazy::force(&TRACING);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = format!("http://{}", listener.local_addr().unwrap());