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

View file

@ -2,6 +2,7 @@ use anyhow::Result;
use chrono::{DateTime, Local};
use clap::Clap;
use humantime::Duration;
use log::info;
use posixmq::PosixMq;
use std::str;
@ -28,10 +29,8 @@ pub struct Recv {
pub queue: String,
}
fn print_message(verbose: bool, priority: u32, length: usize, timestamp: bool, msg: &str) {
if verbose {
println!("Priority: {}, length: {}", priority, length);
}
fn print_message(priority: u32, length: usize, timestamp: bool, msg: &str) {
info!("Priority: {}, length: {}", priority, length);
if timestamp {
println!("{}", Local::now());
@ -41,30 +40,30 @@ fn print_message(verbose: bool, priority: u32, length: usize, timestamp: bool, m
}
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];
if let Some(timeout) = &self.timeout {
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 {
let (prio, len) = mq.recv_deadline(
&mut buf,
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 {
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(())
}
pub fn run(&self, verbose: bool) -> Result<()> {
pub fn run(&self) -> Result<()> {
let mq = &mut posixmq::OpenOptions::readonly();
if self.non_blocking {
@ -75,10 +74,10 @@ impl Recv {
if self.follow {
loop {
self.receive(verbose, &mq)?;
self.receive(&mq)?;
}
} else {
self.receive(verbose, &mq)?;
self.receive(&mq)?;
}
Ok(())