Skip to content

Commit

Permalink
feat: even more tracing
Browse files Browse the repository at this point in the history
  • Loading branch information
ajaxbits committed Apr 24, 2024
1 parent 2b0a7b5 commit 6b61dbd
Show file tree
Hide file tree
Showing 7 changed files with 238 additions and 4 deletions.
71 changes: 69 additions & 2 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ tokio-util = "0.7.4"
tower = "0.4.13"
tower-http = { version = "0.3.4", features = ["fs", "trace"] }
tracing = "0.1.40"
tracing-error = "0.2.0"
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "json"] }
url = "2.5.0"
youtube_dl = { version = "0.7.0", default-features = false, features = [
"yt-dlp",
Expand Down
2 changes: 1 addition & 1 deletion src/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub async fn return_audio(
let dir = path.parent().unwrap();

if let Err(e) = reduce_dir_size(dir, target_dir_size) {
return Err(eyre!("Failed to reduce directory size: {:?}", e))?
return Err(eyre!("Failed to reduce directory size: {:?}", e))?;
}
}

Expand Down
140 changes: 140 additions & 0 deletions src/cli/instrumentation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
use color_eyre::eyre::WrapErr;
use std::{error::Error, io::IsTerminal};
use tracing::Subscriber;
use tracing_subscriber::{
filter::Directive,
layer::{Layer, SubscriberExt},
registry::LookupSpan,
util::SubscriberInitExt,
EnvFilter,
};

use super::logger::Logger;

#[derive(clap::Args, Debug, Default)]
pub(crate) struct Instrumentation {
#[clap(
short='v',
env="VERBOSITY",
long,
action = clap::ArgAction::Count,
global=true
)]
pub verbose: u8,

#[clap(
long,
env = "LOGGER",
default_value_t = Default::default(),
global = true
)]
pub(crate) logger: Logger,

#[clap(
long = "log-filters",
env = "LOG_FILTERS",
value_delimiter = ',',
num_args = 0..,
global = true
)]
pub(crate) log_directives: Vec<Directive>,
}

impl Instrumentation {
pub(crate) fn log_level(&self) -> String {
match self.verbose {
0 => "info",
1 => "debug",
_ => "trace",
}
.to_string()
}

pub(crate) fn setup(&self) -> color_eyre::Result<()> {
let filter_layer = self.filter_layer()?;
let registry = tracing_subscriber::registry()
.with(filter_layer)
.with(tracing_error::ErrorLayer::default());
match self.logger {
Logger::Compact => registry.with(self.fmt_layer_compact()).try_init()?,
Logger::Full => registry.with(self.fmt_layer_full()).try_init()?,
Logger::Pretty => registry.with(self.fmt_layer_pretty()).try_init()?,
Logger::Json => registry.with(self.fmt_layer_json()).try_init()?,
}
Ok(())
}

pub(crate) fn filter_layer(&self) -> color_eyre::Result<EnvFilter> {
let mut filter_layer = match EnvFilter::try_from_default_env() {
Ok(layer) => layer,
Err(e) => {
if let Some(source) = e.source() {
match source.downcast_ref::<std::env::VarError>() {
Some(std::env::VarError::NotPresent) => (),
_ => return Err(e).wrap_err_with(|| "parsing RUST_LOG directives"),
}
}

if self.log_directives.is_empty() {
EnvFilter::try_new(&format!(
"{}={}",
env!("CARGO_PKG_NAME").replace('-', "_"),
self.log_level()
))?
} else {
EnvFilter::try_new("")?
}
}
};

for directive in &self.log_directives {
filter_layer = filter_layer.add_directive(directive.clone())
}
Ok(filter_layer)
}

pub(crate) fn fmt_layer_compact<S>(&self) -> impl Layer<S>
where
S: Subscriber + for<'span> LookupSpan<'span>,
{
tracing_subscriber::fmt::Layer::new()
.with_ansi(std::io::stderr().is_terminal())
.with_writer(std::io::stderr)
.compact()
.without_time()
.with_target(false)
.with_thread_ids(false)
.with_thread_names(false)
.with_file(false)
.with_line_number(false)
}

pub(crate) fn fmt_layer_full<S>(&self) -> impl Layer<S>
where
S: Subscriber + for<'span> LookupSpan<'span>,
{
tracing_subscriber::fmt::Layer::new()
.with_ansi(std::io::stderr().is_terminal())
.with_writer(std::io::stderr)
}

pub(crate) fn fmt_layer_pretty<S>(&self) -> impl Layer<S>
where
S: Subscriber + for<'span> LookupSpan<'span>,
{
tracing_subscriber::fmt::Layer::new()
.with_ansi(std::io::stderr().is_terminal())
.with_writer(std::io::stderr)
.pretty()
}

pub(crate) fn fmt_layer_json<S>(&self) -> impl Layer<S>
where
S: Subscriber + for<'span> LookupSpan<'span>,
{
tracing_subscriber::fmt::Layer::new()
.with_ansi(std::io::stderr().is_terminal())
.with_writer(std::io::stderr)
.json()
}
}
23 changes: 23 additions & 0 deletions src/cli/logger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Thank you to Hoverbear
// https://hoverbear.org/blog/instrumenting-axum-projects/

#[derive(Clone, Default, Debug, clap::ValueEnum)]
pub(crate) enum Logger {
#[default]
Compact,
Full,
Pretty,
Json,
}

impl std::fmt::Display for Logger {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let logger = match self {
Logger::Compact => "compact",
Logger::Full => "full",
Logger::Pretty => "pretty",
Logger::Json => "json",
};
write!(f, "{}", logger)
}
}
3 changes: 3 additions & 0 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ use clap::Parser;
use std::net::{IpAddr, Ipv6Addr};
use url::Url;

mod instrumentation;
mod logger;

const DEFAULT_HOST: IpAddr = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
const DEFAULT_PORT: u16 = 8080;

Expand Down
1 change: 0 additions & 1 deletion treefmt.nix
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
{ ... }:
{
projectRootFile = "flake.nix";
programs = {
Expand Down

0 comments on commit 6b61dbd

Please sign in to comment.