Skip to content

Commit

Permalink
Added more logging capabilities.
Browse files Browse the repository at this point in the history
  • Loading branch information
ray-kast committed Mar 8, 2021
1 parent d760075 commit 25693de
Show file tree
Hide file tree
Showing 7 changed files with 204 additions and 31 deletions.
78 changes: 77 additions & 1 deletion Cargo.lock

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

5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "empress"
version = "1.1.0"
version = "1.1.1"
authors = ["rookie1024 <[email protected]>"]
edition = "2018"
description = "A D-Bus MPRIS daemon for controlling media players."
Expand All @@ -13,10 +13,13 @@ categories = ["command-line-utilities", "multimedia", "os"]

[dependencies]
anyhow = "1.0.38"
atty = "0.2.14"
dbus = "0.9.2"
dbus-crossroads = "0.3.0"
dbus-tokio = "0.7.3"
env_logger = "0.8.3"
futures = "0.3.13"
lazy_static = "1.4.0"
log = "0.4.14"
structopt = "0.3.21"
tokio = { version = "1.2.0", features = ["macros", "rt", "signal", "sync"] }
14 changes: 6 additions & 8 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ use dbus::{
arg::ReadAll,
nonblock::{Proxy, SyncConnection},
strings::Member,
MethodErr,
};
use dbus_tokio::connection;
use log::{info, warn};
use tokio::{select, sync::oneshot, task};

use crate::{ClientCommand, ExtraMethodId, Result, INTERFACE_NAME, SERVER_NAME, SERVER_PATH};
Expand Down Expand Up @@ -61,17 +63,13 @@ async fn try_send<T: ReadAll + 'static, M: for<'a> Into<Member<'a>>>(
let mut i = 0;

loop {
match proxy
.method_call(&*INTERFACE_NAME, &method, ())
.await
.context("failed to contact empress server")
{
Err(e) if i < MAX_TRIES => eprintln!("WARNING: {:?}", e),
r => break r,
match proxy.method_call(&*INTERFACE_NAME, &method, ()).await {
Err(e) if i < MAX_TRIES => warn!("Request failed: {}", e),
r => break r.context("failed to contact empress server"),
}

i += 1;
eprintln!("Retry attempt {:?}", i);
info!("Retry attempt {}", i);

tokio::time::sleep(Duration::from_millis(20)).await;
}
Expand Down
56 changes: 52 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use std::{

use anyhow::{Context, Error};
use lazy_static::lazy_static;
use log::{error, LevelFilter};
use structopt::StructOpt;
use tokio::runtime::Builder as RtBuilder;

Expand Down Expand Up @@ -94,7 +95,25 @@ impl Display for ControlMethodId {
#[derive(StructOpt)]
enum Opts {
/// Launch a D-Bus service abstracting MPRIS players
Server,
Server {
/// Disable info logs (enabled by default if stderr is not a TTY)
#[structopt(short, long)]
quiet: bool,

/// Enable info logs, even if stderr is not a TTY
#[structopt(long, conflicts_with("quiet"))]
no_quiet: bool,

/// Output extra information to the console
#[structopt(
short,
long,
parse(from_occurrences),
conflicts_with("quiet"),
conflicts_with("no-quiet"),
)]
verbose: usize,
},
#[structopt(flatten)]
Client(ClientCommand),
}
Expand All @@ -107,12 +126,27 @@ enum ClientCommand {
Control(ControlMethodId),
}

fn log_cfg(v: usize) -> env_logger::Builder {
const VERBOSITY: [LevelFilter; 3] = [LevelFilter::Info, LevelFilter::Debug, LevelFilter::Trace];
#[cfg(debug_assertions)]
const DEFAULT_V: usize = 1;
#[cfg(not(debug_assertions))]
const DEFAULT_V: usize = 0;

let mut b = env_logger::builder();

b.filter_level(VERBOSITY[(DEFAULT_V + v).min(VERBOSITY.len() - 1)]);
b
}

fn main() {
let result = run();

log_cfg(0).try_init().ok();

match result {
Ok(()) => (),
Err(e) => eprintln!("ERROR: {:?}", e),
Err(e) => error!("{:?}", e),
}
}

Expand All @@ -125,7 +159,21 @@ fn run() -> Result {
let opts = Opts::from_args();

match opts {
Opts::Server => rt.block_on(server::run()),
Opts::Client(id) => rt.block_on(client::run(id)),
Opts::Server { quiet, no_quiet, verbose } => {
let mut log_cfg = log_cfg(verbose);

if !(no_quiet || atty::is(atty::Stream::Stderr)) || quiet {
log_cfg.filter_level(LevelFilter::Warn);
}

log_cfg.init();

rt.block_on(server::run())
},
Opts::Client(id) => {
log_cfg(0).init();

rt.block_on(client::run(id))
},
}
}
25 changes: 20 additions & 5 deletions src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use anyhow::{Context, Error};
use dbus::{channel::MatchingReceiver, message::MatchRule, MethodErr};
use dbus_crossroads::{Crossroads, IfaceBuilder};
use dbus_tokio::connection;
use log::{error, info, warn};
use tokio::{
select,
signal::{unix, unix::SignalKind},
Expand All @@ -21,8 +22,16 @@ mod server;
pub(self) use player::Player;
pub(self) use player_map::PlayerMap;

pub(self) fn method_err(e: impl Into<Error>, msg: impl std::fmt::Display) -> MethodErr {
eprintln!("ERROR: {:?}", e.into().context(msg.to_string()));
pub(self) fn method_err(
method: impl std::fmt::Display,
e: impl Into<Error>,
msg: impl std::fmt::Display,
) -> MethodErr {
error!(
"Method hander for {} failed: {:?}",
method,
e.into().context(msg.to_string())
);
MethodErr::failed(&msg)
}

Expand Down Expand Up @@ -105,7 +114,7 @@ pub async fn run() -> Result {

match cr.handle_message(msg, conn) {
Ok(()) => (),
Err(()) => eprintln!("WARNING: failed to handle message {}", msg_dbg),
Err(()) => warn!("Failed to handle message {}", msg_dbg),
};
true
}),
Expand All @@ -118,15 +127,21 @@ pub async fn run() -> Result {

select!(
Some(()) = hup.recv() => Ok(()),
Some(()) = int.recv() => Ok(()),
Some(()) = int.recv() => {
if atty::is(atty::Stream::Stdin) && atty::is(atty::Stream::Stderr) {
eprintln!();
}

Ok(())
}
Some(()) = quit.recv() => Ok(()),
Some(()) = term.recv() => Ok(()),
res = close_rx => Err(
res.context("lost D-Bus connection resource").map_or_else(|e| e, |e| e)
),
)?;

eprintln!("Shutting down...");
info!("Shutting down...");

Ok(())
}
Loading

0 comments on commit 25693de

Please sign in to comment.