Add a trace layer

This commit is contained in:
Greg Burri 2024-11-03 12:11:33 +01:00
parent 980c5884a4
commit 1f03c01d1d
5 changed files with 26 additions and 21 deletions

View file

@ -1,4 +1,3 @@
* Clean the old code + commit
* How to log error to journalctl or elsewhere + debug log? * How to log error to journalctl or elsewhere + debug log?
* Try using WASM for all the client logic (test on editing/creating a recipe) * Try using WASM for all the client logic (test on editing/creating a recipe)
* Understand the example here: * Understand the example here:
@ -17,6 +16,7 @@
.service(services::webapi::set_recipe_description) .service(services::webapi::set_recipe_description)
* Add support to translations into db model. * Add support to translations into db model.
[ok] Clean the old code + commit
[ok] Reactivate sign up/in/out [ok] Reactivate sign up/in/out
[ok] Change all id to i64 [ok] Change all id to i64
[ok] Check cookie lifetime -> Session by default [ok] Check cookie lifetime -> Session by default

View file

@ -13,6 +13,7 @@ use sqlx::{
Pool, Sqlite, Transaction, Pool, Sqlite, Transaction,
}; };
use thiserror::Error; use thiserror::Error;
use tracing::{event, Level};
use crate::{ use crate::{
consts, consts,
@ -156,7 +157,7 @@ WHERE [type] = 'table' AND [name] = 'Version'
let next_version = current_version + 1; let next_version = current_version + 1;
if next_version <= CURRENT_DB_VERSION { if next_version <= CURRENT_DB_VERSION {
println!("Update to version {}...", next_version); event!(Level::INFO, "Update to version {}...", next_version);
} }
async fn update_version(to_version: u32, tx: &mut Transaction<'_, Sqlite>) -> Result<()> { async fn update_version(to_version: u32, tx: &mut Transaction<'_, Sqlite>) -> Result<()> {
@ -171,7 +172,7 @@ WHERE [type] = 'table' AND [name] = 'Version'
fn ok(updated: bool) -> Result<bool> { fn ok(updated: bool) -> Result<bool> {
if updated { if updated {
println!("Version updated"); event!(Level::INFO, "Version updated");
} }
Ok(updated) Ok(updated)
} }

View file

@ -3,6 +3,7 @@ use lettre::{
transport::smtp::{authentication::Credentials, AsyncSmtpTransport}, transport::smtp::{authentication::Credentials, AsyncSmtpTransport},
AsyncTransport, Message, Tokio1Executor, AsyncTransport, Message, Tokio1Executor,
}; };
use tracing::{event, Level};
use crate::consts; use crate::consts;
@ -57,7 +58,7 @@ pub async fn send_validation(
.build(); .build();
if let Err(error) = mailer.send(email).await { if let Err(error) = mailer.send(email).await {
eprintln!("Error when sending E-mail:\n{:?}", &error); event!(Level::ERROR, "Error when sending E-mail: {}", &error);
} }
Ok(()) Ok(())

View file

@ -11,7 +11,8 @@ use axum_extra::extract::cookie::CookieJar;
use chrono::prelude::*; use chrono::prelude::*;
use clap::Parser; use clap::Parser;
use config::Config; use config::Config;
use tower_http::services::ServeDir; use tower_http::{services::ServeDir, trace::TraceLayer};
use tracing::{event, Level};
use data::db; use data::db;
@ -42,6 +43,12 @@ impl FromRef<AppState> for db::Connection {
} }
} }
#[cfg(debug_assertions)]
const TRACING_LEVEL: tracing::Level = tracing::Level::DEBUG;
#[cfg(not(debug_assertions))]
const TRACING_LEVEL: tracing::Level = tracing::Level::INFO;
// TODO: Should main returns 'Result'? // TODO: Should main returns 'Result'?
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
@ -49,14 +56,16 @@ async fn main() {
return; return;
} }
println!("Starting Recipes as web server..."); tracing_subscriber::fmt()
.with_max_level(TRACING_LEVEL)
.init();
event!(Level::INFO, "Starting Recipes as web server...");
let config = config::load(); let config = config::load();
let port = config.port; let port = config.port;
println!("Configuration: {:?}", config); event!(Level::INFO, "Configuration: {:?}", config);
tracing_subscriber::fmt::init();
let db_connection = db::Connection::new().await.unwrap(); let db_connection = db::Connection::new().await.unwrap();
@ -78,6 +87,7 @@ async fn main() {
get(services::sign_in_get).post(services::sign_in_post), get(services::sign_in_get).post(services::sign_in_post),
) )
.route("/signout", get(services::sign_out)) .route("/signout", get(services::sign_out))
.layer(TraceLayer::new_for_http())
.route_layer(middleware::from_fn_with_state( .route_layer(middleware::from_fn_with_state(
state.clone(), state.clone(),
user_authentication, user_authentication,
@ -117,23 +127,18 @@ async fn get_current_user(
.authentication(token_cookie.value(), &client_ip, &client_user_agent) .authentication(token_cookie.value(), &client_ip, &client_user_agent)
.await .await
{ {
Ok(db::AuthenticationResult::NotValidToken) => { Ok(db::AuthenticationResult::NotValidToken) => None,
// TODO: remove cookie?
None
}
Ok(db::AuthenticationResult::Ok(user_id)) => { Ok(db::AuthenticationResult::Ok(user_id)) => {
match connection.load_user(user_id).await { match connection.load_user(user_id).await {
Ok(user) => user, Ok(user) => user,
Err(error) => { Err(error) => {
// TODO: Return 'Result'? event!(Level::WARN, "Error during authentication: {}", error);
println!("Error during authentication: {}", error);
None None
} }
} }
} }
Err(error) => { Err(error) => {
// TODO: Return 'Result'? event!(Level::WARN, "Error during authentication: {}", error);
println!("Error during authentication: {}", error);
None None
} }
}, },
@ -176,7 +181,7 @@ async fn process_args() -> bool {
match db::Connection::new().await { match db::Connection::new().await {
Ok(con) => { Ok(con) => {
if let Err(error) = con.execute_file("sql/data_test.sql").await { if let Err(error) = con.execute_file("sql/data_test.sql").await {
eprintln!("{}", error); event!(Level::ERROR, "{}", error);
} }
// Set the creation datetime to 'now'. // Set the creation datetime to 'now'.
con.execute_sql( con.execute_sql(
@ -188,7 +193,7 @@ async fn process_args() -> bool {
.unwrap(); .unwrap();
} }
Err(error) => { Err(error) => {
eprintln!("{}", error); event!(Level::ERROR, "{}", error);
} }
} }

View file

@ -305,8 +305,6 @@ pub async fn sign_up_post(
) )
}; };
println!("{}", &url);
let email = form_data.email.clone(); let email = form_data.email.clone();
match email::send_validation( match email::send_validation(
&url, &url,