Skip to content

Commit

Permalink
Make use of enumerated error types for consolidated log level checking
Browse files Browse the repository at this point in the history
  • Loading branch information
ByteOtter committed Aug 14, 2024
1 parent 87d9f92 commit 644eea2
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 81 deletions.
2 changes: 1 addition & 1 deletion isototest/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub async fn create_vnc_client(
.add_encoding(vnc::VncEncoding::Trle)
.add_encoding(vnc::VncEncoding::CursorPseudo)
.add_encoding(vnc::VncEncoding::DesktopSizePseudo)
.allow_shared(true)
.allow_shared(true) // Allow for multiple other VNC sessions to be connected at once.
// NOTE: If the color encoding is changed in the following line, you must also change it in
// view.rs to avoid the saved screenshots from having swapped colors.
.set_pixel_format(PixelFormat::rgba())
Expand Down
20 changes: 14 additions & 6 deletions isototest/src/errors/util_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,24 @@ use std::fmt;

#[derive(Debug)]
#[cfg(feature = "default-logging")]
/// Error used for checking given log level.
/// Only available as part of the `default-logging` feature.
pub struct InvalidLogLevelError(pub String);
pub enum LoggingError {
LoggingInitError(String),
InvalidLogLevelError(String),
}

#[cfg(feature = "default-logging")]
impl fmt::Display for InvalidLogLevelError {
impl fmt::Display for LoggingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[error] Invalid log level: '{}'", self.0)
match self {
LoggingError::LoggingInitError(msg) => {
write!(f, "[error] Logging initialization failed: '{}'", msg)
}
LoggingError::InvalidLogLevelError(msg) => {
write!(f, "[error] Invalid log level: '{}'", msg)
}
}
}
}

#[cfg(feature = "default-logging")]
impl std::error::Error for InvalidLogLevelError {}
impl std::error::Error for LoggingError {}
28 changes: 5 additions & 23 deletions isototest/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,30 +65,12 @@ pub(crate) mod types;

// Provide code on the root level of the library
#[cfg(feature = "default-logging")]
use crate::logging::LOG_TARGET;
use crate::logging::init_default_logging;
#[cfg(feature = "default-logging")]
use log::{debug, trace};
use crate::errors::util_errors::LoggingError;

#[cfg(feature = "default-logging")]
pub fn init_logging(level: Option<&str>) -> Result<(), errors::util_errors::InvalidLogLevelError> {
match level {
Some("debug") => {
logging::init_debug_logging();
debug!(target: LOG_TARGET, "Logging initialized. Running with 'debug' log level.");
Ok(())
}
Some("trace") => {
logging::init_trace();
trace!(target: LOG_TARGET, "Logging initialized. Running with 'trace' log level.");
Ok(())
}
None => {
logging::init_default_logging();
Ok(())
}
Some(invalid) => Err(errors::util_errors::InvalidLogLevelError(format!(
"[error] Invalid log level defined: '{}'",
invalid
))),
}
pub fn init_logging(level: Option<&str>) -> Result<(), LoggingError> {
init_default_logging(level)?;
Ok(())
}
86 changes: 35 additions & 51 deletions isototest/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,69 +4,53 @@
use env_logger::Builder;
#[cfg(feature = "default-logging")]
use std::io::Write;
#[cfg(feature = "default-logging")]
use crate::errors::util_errors::LoggingError;

pub const LOG_TARGET: &str = "[isototest]";

#[cfg(feature = "default-logging")]
/// Initialize default logging configuration.
///
/// By default, we will only log `info` leves and higher.
pub fn init_default_logging() {
Builder::new()
.filter_level(log::LevelFilter::Info)
.format(|buf, record| {
writeln!(
buf,
"{} [{}] {}: {}",
buf.timestamp(),
record.level(),
record.target(),
record.args()
)
})
.init();
}

#[cfg(feature = "default-logging")]
/// Initialize debug logging.
/// Initialize default logging configuration with given log level.
///
/// Will log every event with the `debug` log level and higher.
/// Log Level can be:
/// * "info" - Default log level also adapted if level is `none`. Logs events relevant for general usage.
/// * "debug" - Debug level for extended logging. Should only be used for development purposes.
/// * "trace" - Extensive log evel logging every event. Should only be used for development purposes.
///
/// **Should only be used for development purposes.**
pub fn init_debug_logging() {
Builder::new()
.filter_level(log::LevelFilter::Debug)
.format(|buf, record| {
writeln!(
buf,
"{} [{}] {}: {}",
buf.timestamp(),
record.level(),
record.target(),
record.args()
)
})
.init();
pub(crate) fn init_default_logging(level: Option<&str>) -> Result<(), LoggingError> {
match level {
Some("info") | None => {
log_builder(log::LevelFilter::Info);
Ok(())
},
Some("debug") => {
log_builder(log::LevelFilter::Debug);
Ok(())
},
Some("trace") => {
log_builder(log::LevelFilter::Trace);
Ok(())
},
Some(invalid) => {
Err(LoggingError::InvalidLogLevelError(format!("Invalid log level '{}'!", invalid)))
}
}
}

#[cfg(feature = "default-logging")]
/// Initialize trace.
///
/// Will log every event.
///
/// **Should only be used for development purposes.**
pub fn init_trace() {
fn log_builder(level: log::LevelFilter) {
Builder::new()
.filter_level(log::LevelFilter::Trace)
.filter_level(level)
.format(|buf, record| {
writeln!(
buf,
"{} [{}] {}: {}",
buf.timestamp(),
record.level(),
record.target(),
record.args()
)
buf,
"{} [{}] {}: {}",
buf.timestamp(),
record.level(),
record.target(),
record.args()
)
})
.init();
}

0 comments on commit 644eea2

Please sign in to comment.