1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
pub mod config; use std::str::FromStr; use thiserror::Error; use tracing_subscriber::filter::LevelFilter; use tracing_subscriber::{EnvFilter, FmtSubscriber}; #[derive(Error, Debug)] pub enum LoggerError { #[error("LoggerConfigurationError: [{message}]")] LoggerConfigurationError { message: String }, } impl From<log::SetLoggerError> for LoggerError { fn from(error: log::SetLoggerError) -> Self { LoggerError::LoggerConfigurationError { message: format!("{}", error), } } } impl From<std::io::Error> for LoggerError { fn from(error: std::io::Error) -> Self { LoggerError::LoggerConfigurationError { message: format!("{}", error), } } } pub fn setup_logger(logger_config: &config::LoggerConfig) -> Result<(), LoggerError> { let level = LevelFilter::from_str(&logger_config.level).map_err(|err| { LoggerError::LoggerConfigurationError { message: format!( "The specified logger level is not valid: [{}]. err: {}", &logger_config.level, err ), } })?; if logger_config.stdout_output { if let Some(env_filter) = &logger_config.env_filter { let env_filter = EnvFilter::from_str(env_filter) .map_err(|err| LoggerError::LoggerConfigurationError { message: format!( "Cannot parse the env_filter: [{}]. err: {}", env_filter, err ), })? .add_directive(level.into()); FmtSubscriber::builder() .with_env_filter(env_filter) .try_init() .map_err(|err| LoggerError::LoggerConfigurationError { message: format!("Cannot start the stdout_output logger. err: {}", err), })?; } else { FmtSubscriber::builder() .with_max_level(level) .try_init() .map_err(|err| LoggerError::LoggerConfigurationError { message: format!("Cannot start the stdout_output logger. err: {}", err), })?; } } Ok(()) }