Skip to content

Commit

Permalink
Merge pull request #38 from hartwork/move-log-styling-into-logger
Browse files Browse the repository at this point in the history
logging.rs: Move log styling into logging module
  • Loading branch information
hartwork authored Jun 23, 2023
2 parents 1dc0954 + edae441 commit bb1f930
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 14 deletions.
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ anstream = "0.3.2"
clap = { version = "4.3.4", features = ["cargo", "color"] }
indoc = "2.0.1"
lazy_static = "1.4.0"
log = { version = "0.4.19" }
log = { version = "0.4.19", features = ["kv_unstable"] }
regex = "1.8.4"
subprocess = "0.2.9"

Expand Down
6 changes: 3 additions & 3 deletions src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ fn process_popen_result(popen_result: PopenResult<ExitStatus>, command: &str) ->
match popen_result {
Ok(exit_status) => exit_code_from(exit_status),
Err(PopenError::IoError(error)) if error.kind() == ErrorKind::PermissionDenied => {
error!("[-] Command '{command}' could not be run: permission denied.");
error!("Command '{command}' could not be run: permission denied.");
126
}
Err(PopenError::IoError(error)) if error.kind() == ErrorKind::NotFound => {
error!("[-] Command '{command}' not found.");
error!("Command '{command}' not found.");
127
}
Err(error) => {
error!("[-] Command '{command}' failed with unexpected error: {error}.");
error!("Command '{command}' failed with unexpected error: {error}.");
255
}
}
Expand Down
62 changes: 57 additions & 5 deletions src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,52 @@
// Copyright (c) 2023 Sebastian Pipping <sebastian@pipping.org>
// SPDX-License-Identifier: MIT

use log::{set_logger, set_max_level, Level, LevelFilter, Log, Metadata, Record};
use log::{kv::ToValue, kv::Value, set_logger, set_max_level, LevelFilter, Log, Metadata, Record};

static CUSTOM_LOG: CustomLog = CustomLog {};

struct CustomLog {}

#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) enum SubLevel {
Starting,
Succeeded,
Failed,
}

impl From<u64> for SubLevel {
fn from(value: u64) -> Self {
match value {
0 => SubLevel::Starting,
1 => SubLevel::Succeeded,
_ => SubLevel::Failed,
}
}
}

impl ToValue for SubLevel {
fn to_value(&self) -> Value {
match self {
SubLevel::Starting => 0u64.to_value(),
SubLevel::Succeeded => 1u64.to_value(),
SubLevel::Failed => 2u64.to_value(),
}
}
}

#[cfg(test)]
#[test]
fn test_sublevel_casting() {
assert_eq!(SubLevel::Starting.to_value().to_u64().unwrap(), 0);
assert_eq!(SubLevel::Succeeded.to_value().to_u64().unwrap(), 1);
assert_eq!(SubLevel::Failed.to_value().to_u64().unwrap(), 2);

assert_eq!(SubLevel::from(0), SubLevel::Starting);
assert_eq!(SubLevel::from(1), SubLevel::Succeeded);
assert_eq!(SubLevel::from(2), SubLevel::Failed);
assert_eq!(SubLevel::from(3), SubLevel::Failed);
}

impl Log for CustomLog {
fn enabled(&self, _metadata: &Metadata) -> bool {
true
Expand All @@ -19,10 +59,22 @@ impl Log for CustomLog {
return;
}

if record.level() == Level::Error {
eprintln!("{}", record.args());
} else {
println!("{}", record.args());
let value: Value = record
.key_values()
.get("sublevel".into())
.unwrap_or(Value::from(SubLevel::Failed as u64));
let sublevel = SubLevel::from(value.to_u64().expect("malformed sublevel"));

match sublevel {
SubLevel::Starting => {
println!("[*] {}", record.args());
}
SubLevel::Succeeded => {
println!("[+] {}", record.args());
}
SubLevel::Failed => {
eprintln!("[-] {}", record.args());
}
}
}

Expand Down
14 changes: 9 additions & 5 deletions src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// Copyright (c) 2023 Sebastian Pipping <sebastian@pipping.org>
// SPDX-License-Identifier: MIT

use crate::logging::SubLevel;
use log::{error, info};
use std::io;
use std::net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs};
Expand Down Expand Up @@ -124,9 +125,11 @@ pub(crate) fn wait_for_service(
let forever = timeout_seconds == 0;

if forever {
info!("[*] Waiting for {host_and_port} without a timeout...");
info!(target: module_path!(), sublevel = SubLevel::Starting;
"Waiting for {host_and_port} without a timeout...");
} else {
info!("[*] Waiting {timeout_seconds} seconds for {host_and_port}...");
info!(target: module_path!(), sublevel = SubLevel::Starting;
"Waiting {timeout_seconds} seconds for {host_and_port}...");
}

let timeout = if timeout_seconds == 0 {
Expand All @@ -140,12 +143,13 @@ pub(crate) fn wait_for_service(
match connect_result {
Ok(_) => {
let duration = timer.elapsed().as_secs();
info!("[+] {host_and_port} is available after {duration} seconds.");
info!(target: module_path!(), sublevel = SubLevel::Succeeded;
"{host_and_port} is available after {duration} seconds.");
}
Err(ref error) => {
error!(
"[-] {host_and_port} timed out after waiting for {timeout_seconds} seconds ({error})."
);
"{host_and_port} timed out after waiting for {timeout_seconds} seconds ({error})."
);
}
}

Expand Down

0 comments on commit bb1f930

Please sign in to comment.