Refactor logging

To supporte more than a single log level `log` and `env_logger` crates
are used. For the application to support the different type of
argument, the verbose argument definition was adapted.
This commit is contained in:
finga 2021-07-07 17:13:08 +02:00
parent 6a41335603
commit 12b117db7e
8 changed files with 107 additions and 36 deletions

64
Cargo.lock generated
View file

@ -1,5 +1,16 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3
[[package]]
name = "aho-corasick"
version = "0.7.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.41" version = "1.0.41"
@ -29,6 +40,12 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.19" version = "0.4.19"
@ -74,6 +91,19 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "env_logger"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3"
dependencies = [
"atty",
"humantime",
"log",
"regex",
"termcolor",
]
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.11.2" version = "0.11.2"
@ -126,6 +156,21 @@ version = "0.2.97"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12b8adadd720df158f4d70dfe7ccc6adb0472d7c55ca83445f6a5ab3e36f8fb6" checksum = "12b8adadd720df158f4d70dfe7ccc6adb0472d7c55ca83445f6a5ab3e36f8fb6"
[[package]]
name = "log"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710"
dependencies = [
"cfg-if",
]
[[package]]
name = "memchr"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b16bd47d9e329435e309c58469fe0791c2d0d1ba96ec0954152a5ae2b04387dc"
[[package]] [[package]]
name = "mqrs" name = "mqrs"
version = "0.1.1" version = "0.1.1"
@ -133,7 +178,9 @@ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",
"clap", "clap",
"env_logger",
"humantime", "humantime",
"log",
"posixmq", "posixmq",
] ]
@ -213,6 +260,23 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "regex"
version = "1.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.6.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b"
[[package]] [[package]]
name = "strsim" name = "strsim"
version = "0.10.0" version = "0.10.0"

View file

@ -13,6 +13,8 @@ clap = "3.0.0-beta.2"
posixmq = "1.0" posixmq = "1.0"
chrono = "0.4" chrono = "0.4"
humantime = "2.1" humantime = "2.1"
log = "0.4"
env_logger = "0.8"
[package.metadata.deb] [package.metadata.deb]
extended-description = "`mqrs` is a small cli application to handle POSIX message queues." extended-description = "`mqrs` is a small cli application to handle POSIX message queues."

3
mqrs.1
View file

@ -26,7 +26,8 @@ completed further.
Prints help information Prints help information
.TP 8 .TP 8
.B \-v, \-\-verbose .B \-v, \-\-verbose
Produce verbose output Produce verbose output, multiple -v options increase the verbosity
(max. 3)
.TP 8 .TP 8
.B \-V, \-\-version .B \-V, \-\-version
Prints version information Prints version information

View file

@ -21,9 +21,9 @@ enum Command {
global_setting = AppSettings::InferSubcommands, global_setting = AppSettings::InferSubcommands,
)] )]
struct Opts { struct Opts {
/// Produce verbose output /// Produce verbose output, multiple -v options increase the verbosity (max. 3)
#[clap(short, long, global = true)] #[clap(short, long, global = true, parse(from_occurrences))]
verbose: bool, verbose: u32,
#[clap(subcommand)] #[clap(subcommand)]
command: Command, command: Command,
} }
@ -31,12 +31,22 @@ struct Opts {
fn main() -> Result<()> { fn main() -> Result<()> {
let opts: Opts = Opts::parse(); let opts: Opts = Opts::parse();
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(
match opts.verbose {
0 => "warn",
1 => "info",
2 => "debug",
_ => "trace",
},
))
.init();
match opts.command { match opts.command {
Command::Create(c) => c.run(opts.verbose)?, Command::Create(c) => c.run()?,
Command::Info(i) => i.run()?, Command::Info(i) => i.run()?,
Command::Unlink(u) => u.run(opts.verbose)?, Command::Unlink(u) => u.run()?,
Command::Send(s) => s.run(opts.verbose)?, Command::Send(s) => s.run()?,
Command::Recv(r) => r.run(opts.verbose)?, Command::Recv(r) => r.run()?,
} }
Ok(()) Ok(())

View file

@ -1,5 +1,6 @@
use anyhow::Result; use anyhow::Result;
use clap::Clap; use clap::Clap;
use log::{info, log_enabled, Level::Info};
use posixmq::PosixMq; use posixmq::PosixMq;
use std::fs; use std::fs;
@ -35,7 +36,7 @@ fn msg_default() -> usize {
} }
impl Create { impl Create {
pub fn run(&self, verbose: bool) -> Result<()> { pub fn run(&self) -> Result<()> {
let mq = &mut posixmq::OpenOptions::readonly(); let mq = &mut posixmq::OpenOptions::readonly();
if let Some(m) = &self.permissions { if let Some(m) = &self.permissions {
@ -47,11 +48,11 @@ impl Create {
.create_new() .create_new()
.open(&self.queue)?; .open(&self.queue)?;
if verbose { if log_enabled!(Info) {
let mq = PosixMq::open(&self.queue)?; let mq = PosixMq::open(&self.queue)?;
let attributes = mq.attributes()?; let attributes = mq.attributes()?;
println!("Created message queue: {} with attributes msgsize: {}, capacity: {}, current_messages: {}", info!("Created message queue: {} with attributes msgsize: {}, capacity: {}, current_messages: {}",
&self.queue, &self.queue,
&attributes.max_msg_len, &attributes.max_msg_len,
&attributes.capacity, &attributes.capacity,

View file

@ -2,6 +2,7 @@ use anyhow::Result;
use chrono::{DateTime, Local}; use chrono::{DateTime, Local};
use clap::Clap; use clap::Clap;
use humantime::Duration; use humantime::Duration;
use log::info;
use posixmq::PosixMq; use posixmq::PosixMq;
use std::str; use std::str;
@ -28,10 +29,8 @@ pub struct Recv {
pub queue: String, pub queue: String,
} }
fn print_message(verbose: bool, priority: u32, length: usize, timestamp: bool, msg: &str) { fn print_message(priority: u32, length: usize, timestamp: bool, msg: &str) {
if verbose { info!("Priority: {}, length: {}", priority, length);
println!("Priority: {}, length: {}", priority, length);
}
if timestamp { if timestamp {
println!("{}", Local::now()); println!("{}", Local::now());
@ -41,30 +40,30 @@ fn print_message(verbose: bool, priority: u32, length: usize, timestamp: bool, m
} }
impl Recv { impl Recv {
fn receive(&self, verbose: bool, mq: &PosixMq) -> Result<()> { fn receive(&self, mq: &PosixMq) -> Result<()> {
let mut buf = vec![0; mq.attributes()?.max_msg_len]; let mut buf = vec![0; mq.attributes()?.max_msg_len];
if let Some(timeout) = &self.timeout { if let Some(timeout) = &self.timeout {
let (prio, len) = mq.recv_timeout(&mut buf, *timeout.parse::<Duration>()?)?; let (prio, len) = mq.recv_timeout(&mut buf, *timeout.parse::<Duration>()?)?;
print_message(verbose, prio, len, self.timestamp, str::from_utf8(&buf)?); print_message(prio, len, self.timestamp, str::from_utf8(&buf)?);
} else if let Some(deadline) = &self.deadline { } else if let Some(deadline) = &self.deadline {
let (prio, len) = mq.recv_deadline( let (prio, len) = mq.recv_deadline(
&mut buf, &mut buf,
DateTime::parse_from_str(deadline, "%Y-%m-%d %H:%M:%S")?.into(), DateTime::parse_from_str(deadline, "%Y-%m-%d %H:%M:%S")?.into(),
)?; )?;
print_message(verbose, prio, len, self.timestamp, str::from_utf8(&buf)?); print_message(prio, len, self.timestamp, str::from_utf8(&buf)?);
} else { } else {
let (prio, len) = mq.recv(&mut buf)?; let (prio, len) = mq.recv(&mut buf)?;
print_message(verbose, prio, len, self.timestamp, str::from_utf8(&buf)?); print_message(prio, len, self.timestamp, str::from_utf8(&buf)?);
} }
Ok(()) Ok(())
} }
pub fn run(&self, verbose: bool) -> Result<()> { pub fn run(&self) -> Result<()> {
let mq = &mut posixmq::OpenOptions::readonly(); let mq = &mut posixmq::OpenOptions::readonly();
if self.non_blocking { if self.non_blocking {
@ -75,10 +74,10 @@ impl Recv {
if self.follow { if self.follow {
loop { loop {
self.receive(verbose, &mq)?; self.receive(&mq)?;
} }
} else { } else {
self.receive(verbose, &mq)?; self.receive(&mq)?;
} }
Ok(()) Ok(())

View file

@ -2,6 +2,7 @@ use anyhow::Result;
use chrono::DateTime; use chrono::DateTime;
use clap::Clap; use clap::Clap;
use humantime::Duration; use humantime::Duration;
use log::info;
/// Send a message to a message queue /// Send a message to a message queue
#[derive(Clap, Debug)] #[derive(Clap, Debug)]
@ -26,14 +27,8 @@ pub struct Send {
pub msg: String, pub msg: String,
} }
fn print_verbose(verbose: bool, msg: &str, queue: &str) {
if verbose {
println!("Sent message: \"{}\" to queue: {}", &msg, &queue);
}
}
impl Send { impl Send {
pub fn run(&self, verbose: bool) -> Result<()> { pub fn run(&self) -> Result<()> {
let mq = &mut posixmq::OpenOptions::writeonly(); let mq = &mut posixmq::OpenOptions::writeonly();
if self.non_blocking { if self.non_blocking {
@ -47,7 +42,7 @@ impl Send {
*timeout.parse::<Duration>()?, *timeout.parse::<Duration>()?,
)?; )?;
print_verbose(verbose, &self.msg, &self.queue); info!("Sent message: \"{}\" to queue: {}", &self.msg, &self.queue);
} else if let Some(deadline) = &self.deadline { } else if let Some(deadline) = &self.deadline {
mq.open(&self.queue)?.send_deadline( mq.open(&self.queue)?.send_deadline(
self.priority, self.priority,
@ -55,12 +50,12 @@ impl Send {
DateTime::parse_from_str(deadline, "%Y-%m-%d %H:%M:%S")?.into(), DateTime::parse_from_str(deadline, "%Y-%m-%d %H:%M:%S")?.into(),
)?; )?;
print_verbose(verbose, &self.msg, &self.queue); info!("Sent message: \"{}\" to queue: {}", &self.msg, &self.queue);
} else { } else {
mq.open(&self.queue)? mq.open(&self.queue)?
.send(self.priority, &self.msg.as_bytes())?; .send(self.priority, &self.msg.as_bytes())?;
print_verbose(verbose, &self.msg, &self.queue); info!("Sent message: \"{}\" to queue: {}", &self.msg, &self.queue);
} }
Ok(()) Ok(())

View file

@ -1,5 +1,6 @@
use anyhow::Result; use anyhow::Result;
use clap::Clap; use clap::Clap;
use log::info;
/// Delete a message queue /// Delete a message queue
#[derive(Clap, Debug)] #[derive(Clap, Debug)]
@ -10,12 +11,10 @@ pub struct Unlink {
} }
impl Unlink { impl Unlink {
pub fn run(&self, verbose: bool) -> Result<()> { pub fn run(&self) -> Result<()> {
posixmq::remove_queue(&self.queue)?; posixmq::remove_queue(&self.queue)?;
if verbose { info!("Removed message queue: {}", &self.queue);
println!("Removed message queue: {}", &self.queue);
}
Ok(()) Ok(())
} }