Skip to content

Commit

Permalink
feat: allow for setting log level filter via cmdline ez clap (#231)
Browse files Browse the repository at this point in the history
  • Loading branch information
hrzlgnm authored Aug 25, 2024
1 parent b8d7d53 commit 8cf6ac8
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 32 deletions.
1 change: 1 addition & 0 deletions .codespellignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
mut
thead
crate
11 changes: 6 additions & 5 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,17 @@ edition = "2021"
tauri-build = { version = "1.5.3", features = [] }

[dependencies]
clap = { version = "4.5.16", features = ["derive"] }
mdns-sd = { version = "0.11.3", features = ["async", "log"] }
tauri = { version = "1.7.1", features = [
"window-all",
"process-relaunch",
"process-exit",
"dialog-ask",
"shell-open",
"updater",
"http-api",
"http-request",
"process-exit",
"process-relaunch",
"shell-open",
"updater",
"window-all",
] }
serde = { version = "1.0.208", features = ["derive"] }
serde_json = "1.0.125"
Expand Down
107 changes: 81 additions & 26 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use log::LevelFilter;
use clap::builder::TypedValueParser as _;
use clap::Parser;
use mdns_sd::{ServiceDaemon, ServiceEvent, ServiceInfo};
use serde::Serialize;
use std::{
Expand All @@ -15,12 +16,12 @@ use tauri_plugin_log::LogTarget;

type SharedServiceDaemon = Arc<Mutex<ServiceDaemon>>;

struct MdnsState {
struct ManagedState {
daemon: SharedServiceDaemon,
running_browsers: Arc<Mutex<Vec<String>>>,
}

impl MdnsState {
impl ManagedState {
fn new() -> Self {
Self {
daemon: get_shared_daemon(),
Expand Down Expand Up @@ -73,12 +74,7 @@ fn string_with_control_characters_escaped(input: String) -> String {

fn bytes_option_to_string_option_with_escaping(maybe_bytes: Option<&[u8]>) -> Option<String> {
maybe_bytes.map(|bytes| match String::from_utf8(bytes.to_vec()) {
Ok(utf8_string) => {
let result = string_with_control_characters_escaped(utf8_string);
log::debug!("bytes {:#?} -> str {}", bytes, result);

result
}
Ok(utf8_string) => string_with_control_characters_escaped(utf8_string),
Err(_) => byte_array_hexlified(bytes),
})
}
Expand All @@ -98,12 +94,9 @@ impl From<&ServiceInfo> for ResolvedService {
let mut sorted_txt: Vec<TxtRecord> = info
.get_properties()
.iter()
.map(|r| {
log::debug!("txt prop {:#?}", r.val());
TxtRecord {
key: r.key().into(),
val: bytes_option_to_string_option_with_escaping(r.val()),
}
.map(|r| TxtRecord {
key: r.key().into(),
val: bytes_option_to_string_option_with_escaping(r.val()),
})
.collect();
sorted_txt.sort_by(|a, b| a.key.partial_cmp(&b.key).unwrap());
Expand Down Expand Up @@ -149,7 +142,7 @@ type ServiceTypeRemovedEvent = SearchStartedEvent;
const META_SERVICE: &str = "_services._dns-sd._udp.local.";

#[tauri::command]
fn browse_types(window: Window, state: State<MdnsState>) {
fn browse_types(window: Window, state: State<ManagedState>) {
if let Ok(mdns) = state.daemon.lock() {
let mdns_for_thread = mdns.clone();
std::thread::spawn(move || {
Expand Down Expand Up @@ -194,7 +187,7 @@ fn browse_types(window: Window, state: State<MdnsState>) {
}

#[tauri::command]
fn stop_browse(service_type: String, state: State<MdnsState>) {
fn stop_browse(service_type: String, state: State<ManagedState>) {
if service_type.is_empty() {
return;
}
Expand All @@ -210,7 +203,7 @@ fn stop_browse(service_type: String, state: State<MdnsState>) {
}

#[tauri::command]
fn browse(service_type: String, window: Window, state: State<MdnsState>) {
fn browse(service_type: String, window: Window, state: State<ManagedState>) {
if service_type.is_empty() {
return;
}
Expand Down Expand Up @@ -277,7 +270,7 @@ fn browse(service_type: String, window: Window, state: State<MdnsState>) {
const METRIC_SEND_INTERVAL: Duration = Duration::from_secs(10);

#[tauri::command]
fn send_metrics(window: Window, state: State<MdnsState>) {
fn send_metrics(window: Window, state: State<ManagedState>) {
if let Ok(mdns) = state.daemon.lock() {
let mdns_for_thread = mdns.clone();
std::thread::spawn(move || loop {
Expand Down Expand Up @@ -312,10 +305,78 @@ fn platform_setup() {
#[cfg(not(target_os = "linux"))]
fn platform_setup() {}

#[derive(Parser, Debug)]
struct Args {
#[arg(
short = 'l',
long,
default_value_t = foreign_crate::LevelFilter::Info,
value_parser = clap::builder::PossibleValuesParser::new(["trace", "debug", "info", "warn", "error"])
.map(|s| s.parse::<foreign_crate::LevelFilter>().unwrap_or(foreign_crate::LevelFilter::Info)),
)]
log_level: foreign_crate::LevelFilter,
}

mod foreign_crate {
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum LevelFilter {
Trace,
Debug,
Info,
Warn,
Error,
}

impl std::fmt::Display for LevelFilter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::Trace => "trace",
Self::Debug => "debug",
Self::Info => "info",
Self::Warn => "warn",
Self::Error => "error",
};
s.fmt(f)
}
}
impl std::str::FromStr for LevelFilter {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"trace" => Ok(Self::Trace),
"debug" => Ok(Self::Debug),
"info" => Ok(Self::Info),
"warn" => Ok(Self::Warn),
"error" => Ok(Self::Error),
_ => Err(format!("Unknown log level: {s}")),
}
}
}
impl From<LevelFilter> for log::LevelFilter {
fn from(val: LevelFilter) -> Self {
match val {
LevelFilter::Trace => log::LevelFilter::Trace,
LevelFilter::Debug => log::LevelFilter::Debug,
LevelFilter::Info => log::LevelFilter::Info,
LevelFilter::Warn => log::LevelFilter::Warn,
LevelFilter::Error => log::LevelFilter::Error,
}
}
}
}

fn main() {
platform_setup();
let args = Args::parse();
tauri::Builder::default()
.manage(MdnsState::new())
.manage(ManagedState::new())
.plugin(
tauri_plugin_log::Builder::default()
.targets([LogTarget::LogDir, LogTarget::Stdout, LogTarget::Webview])
.level(args.log_level)
.build(),
)
.setup(|app| {
let splashscreen_window = app.get_window("splashscreen").unwrap();
let main_window = app.get_window("main").unwrap();
Expand All @@ -333,12 +394,6 @@ fn main() {
});
Ok(())
})
.plugin(
tauri_plugin_log::Builder::default()
.targets([LogTarget::LogDir, LogTarget::Stdout, LogTarget::Webview])
.level(LevelFilter::Info)
.build(),
)
.invoke_handler(tauri::generate_handler![
browse,
browse_types,
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use app::*;
use leptos::*;

fn main() {
_ = console_log::init_with_level(log::Level::Info);
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to_body(|| {
view! { <App/> }
Expand Down

0 comments on commit 8cf6ac8

Please sign in to comment.