Rust API - Adding Logs with Rust - Part VIII
At this moment, we’ll work directly on our main.rs calling our Logger middleware:
use actix_web::{
web,
App,
HttpServer,
middleware::Logger
};
And then inside our main function, we’ll call our logger looking at the requests we’re calling:
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var("RUST_LOG", "actix_web=info");
}
dotenv().ok();
env_logger::init();
And our HttpServer, at the end of it, will have a wrapper to observe our requests:
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(AppState { db: pool.clone() }))
.configure(services::config)
.wrap(Logger::default()) // <- here
})
.bind(("127.0.0.1", 8080))?
.run().await
Our entire file will look like this:
src/main.rs
mod services;
mod model;
mod schema;
use actix_web::{
web,
App,
HttpServer,
middleware::Logger
};
use dotenv::dotenv;
use sqlx::{ postgres::PgPoolOptions, Pool, Postgres };
pub struct AppState {
db: Pool<Postgres>,
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var("RUST_LOG", "actix_web=info");
}
dotenv().ok();
env_logger::init();
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let pool = match PgPoolOptions::new().max_connections(10).connect(&database_url).await {
Ok(pool) => {
println!("Connection DB resolved");
pool
}
Err(error) => {
println!("Failed to connect to the dabase: {:?}", error);
std::process::exit(1);
}
};
println!("Server started successfully");
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(AppState { db: pool.clone() }))
.configure(services::config)
.wrap(Logger::default())
})
.bind(("127.0.0.1", 8080))?
.run().await
}
And if you run the healthchecker you’ll see logs like this:
[2023-06-12T20:02:46Z INFO actix_web::middleware::logger] 127.0.0.1 "GET /api/healthchecker HTTP/1.1" 200 77 "-" "insomnia/2023.2.2" 0.000361
Well, that’s it, at least I’ll stop here haha. Happy for me that I finished haha and if you liked it, happy for you who read this far, big hug and see you later =]