contact-form/src/logging.rs

52 lines
1.5 KiB
Rust
Raw Normal View History

2023-02-23 02:22:31 +00:00
use anyhow::{Context, Result};
use std::fs::OpenOptions;
use time::{format_description::well_known::Rfc3339, UtcOffset};
use tracing_subscriber::{
filter::LevelFilter,
fmt::{self, time::OffsetTime},
layer::SubscriberExt,
util::SubscriberInitExt,
Layer,
};
2023-02-23 16:17:25 +00:00
/// Initializes the logger.
2023-02-23 02:22:31 +00:00
pub fn init_logger(log_file: &str, utc_offset_hours: i8, utc_offset_minutes: i8) -> Result<()> {
2023-02-23 16:17:25 +00:00
// Set UTC offset for time formatting.
2023-02-23 02:22:31 +00:00
let timer = OffsetTime::new(
UtcOffset::from_hms(utc_offset_hours, utc_offset_minutes, 0)
.context("Failed to set the time offset from the given utc_hours_offset!")?,
Rfc3339,
);
2023-02-23 16:17:25 +00:00
// Use the DEBUG level in debug builds.
2023-02-23 02:22:31 +00:00
let stdout_level_filter = if cfg!(debug_assertions) {
LevelFilter::DEBUG
} else {
LevelFilter::INFO
};
2023-02-23 16:17:25 +00:00
// Stdout logger.
2023-02-23 02:22:31 +00:00
let stdout_layer = fmt::layer()
.with_ansi(true)
.with_timer(timer.clone())
.with_filter(stdout_level_filter);
2023-02-23 16:17:25 +00:00
// Log file.
2023-02-23 02:22:31 +00:00
let log_file = OpenOptions::new()
.create(true)
.append(true)
.open(log_file)
.context("Failed to open the log file in append mode!")?;
let file_layer = fmt::layer()
.with_writer(log_file)
.with_ansi(false)
.with_timer(timer)
.with_filter(LevelFilter::INFO);
2023-02-23 02:22:31 +00:00
tracing_subscriber::registry()
.with(stdout_layer.and_then(file_layer))
.try_init()
.context("Failed to initialize logging!")?;
Ok(())
}