Adds logging to file

This commit is contained in:
2025-10-30 11:18:51 +01:00
parent 076cf40b07
commit 26cb29d7ff

View File

@@ -20,6 +20,9 @@ use std::str::FromStr;
#[macro_use]
extern crate rocket;
extern crate fern;
#[macro_use]
extern crate log;
#[get("/")]
async fn index(state: &State<AppState>) -> Result<NamedFile, Status> {
@@ -28,11 +31,11 @@ async fn index(state: &State<AppState>) -> Result<NamedFile, Status> {
.map_err(|_| Status::InternalServerError)
}
fn setup_logging() -> Result<(), fern::InitError> {
fn setup_logging(log_file: Option<String>) -> Result<(), fern::InitError> {
let level_raw = env::var("LOG_LEVEL").unwrap_or("INFO".to_string());
let level = log::LevelFilter::from_str(&level_raw).expect("LOG_LEVEL invalid");
fern::Dispatch::new()
let log = fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{} {} [{}] {}",
@@ -43,8 +46,13 @@ fn setup_logging() -> Result<(), fern::InitError> {
))
})
.level(level)
.chain(std::io::stdout())
.apply()?;
.chain(std::io::stdout());
if let Some(log_file) = log_file {
log.chain(fern::log_file(log_file)?).apply()?;
} else {
log.apply()?;
}
Ok(())
}
@@ -52,7 +60,9 @@ fn setup_logging() -> Result<(), fern::InitError> {
#[launch]
fn rocket() -> _ {
dotenv::dotenv().ok();
setup_logging().expect("Failed to setup logging");
let log_file = env::var("LOG_FILE");
setup_logging(log_file.ok()).expect("Failed to setup logging");
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let static_dir = env::var("STATIC_DIR").expect("STATIC_DIR must be set");