summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2021-03-10 20:53:48 +0100
committerGitHub <noreply@github.com>2021-03-10 20:53:48 +0100
commit48a9ac895b6e8b01622810ec4bf2f3a423426ca3 (patch)
tree256d152bd7161085264675851ca81d991917f0f2 /src
parented24f917ffabfead27d8b5899e29b55eff2810cc (diff)
parent6f329557aff3c7810699bf1bafa0a073798e1b9f (diff)
Merge pull request #10 from gico-net/feat/configure-logging
Add logging into the application
Diffstat (limited to 'src')
-rw-r--r--src/config.rs18
-rw-r--r--src/main.rs30
2 files changed, 42 insertions, 6 deletions
diff --git a/src/config.rs b/src/config.rs
index 7146a0b..e6cd0bd 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -1,5 +1,9 @@
pub use config::ConfigError;
+use deadpool_postgres::Pool;
use serde::Deserialize;
+use slog::{o, Drain, Logger};
+use slog_async;
+use slog_term;
#[derive(Deserialize)]
pub struct ServerConfig {
@@ -19,4 +23,18 @@ impl Config {
cfg.merge(config::Environment::new())?;
cfg.try_into()
}
+
+ pub fn logging() -> Logger {
+ let decorator = slog_term::TermDecorator::new().build();
+ let drain = slog_term::FullFormat::new(decorator).build().fuse();
+ let drain = slog_async::Async::new(drain).build().fuse();
+
+ slog::Logger::root(drain, o!())
+ }
+}
+
+#[derive(Clone)]
+pub struct AppState {
+ pub pool: Pool,
+ pub log: slog::Logger,
}
diff --git a/src/main.rs b/src/main.rs
index 51c2f6d..0b3d67f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,10 +1,17 @@
mod config;
-use actix_web::{web, App, HttpResponse, HttpServer};
+use actix_web::{middleware, web, App, HttpServer};
use dotenv::dotenv;
+use slog::info;
use tokio_postgres::NoTls;
-use crate::config::Config;
+use crate::config::{Config, AppState};
+
+async fn index(state: web::Data<AppState>) -> &'static str {
+ info!(state.log, "GET `/` page");
+
+ "Hello from Rust!"
+}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
@@ -12,12 +19,23 @@ async fn main() -> std::io::Result<()> {
let config = Config::from_env().unwrap();
let pool = config.pg.create_pool(NoTls).unwrap();
+ let log = Config::logging();
+
+ info!(
+ log,
+ "Starting server at http://{}:{}",
+ config.server.host,
+ config.server.port
+ );
HttpServer::new(move || {
- App::new().data(pool.clone()).service(
- web::resource("/")
- .to(|| HttpResponse::Ok().body("Hello from Rust!")),
- )
+ App::new()
+ .data(AppState {
+ pool: pool.clone(),
+ log: log.clone(),
+ })
+ .wrap(middleware::Logger::default())
+ .route("/", web::get().to(index))
})
.bind(format!("{}:{}", config.server.host, config.server.port))?
.run()