Skip to content

Commit

Permalink
feat: implement logging into a file
Browse files Browse the repository at this point in the history
Signed-off-by: Martichou <m@rtin.fyi>
  • Loading branch information
Martichou committed Mar 2, 2024
1 parent 8f11566 commit 1f7c986
Show file tree
Hide file tree
Showing 8 changed files with 197 additions and 48 deletions.
4 changes: 2 additions & 2 deletions core_lib/src/bin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
extern crate log;

use rqs_lib::RQS;
use tokio::sync::mpsc;
use tokio::sync::broadcast;

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
Expand All @@ -21,7 +21,7 @@ async fn main() -> Result<(), anyhow::Error> {
let mut rqs = RQS::default();
rqs.run().await?;

let discovery_channel = mpsc::channel(10);
let discovery_channel = broadcast::channel(10);
rqs.discovery(discovery_channel.0)?;

// Wait for CTRL+C and then stop RQS
Expand Down
3 changes: 1 addition & 2 deletions core_lib/src/hdl/ble.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ use btleplug::platform::{Adapter, Manager};
use futures::stream::StreamExt;
use tokio::sync::broadcast::Sender;
use tokio_util::sync::CancellationToken;
use uuid::uuid;
use uuid::Uuid;
use uuid::{uuid, Uuid};

const SERVICE_UUID_SHARING: Uuid = uuid!("0000fe2c-0000-1000-8000-00805f9b34fb");

Expand Down
13 changes: 8 additions & 5 deletions core_lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,10 @@ impl RQS {
Ok(send_channel.0)
}

pub fn discovery(&mut self, sender: mpsc::Sender<EndpointInfo>) -> Result<(), anyhow::Error> {
pub fn discovery(
&mut self,
sender: broadcast::Sender<EndpointInfo>,
) -> Result<(), anyhow::Error> {
let ctk = CancellationToken::new();
self.discovery_ctk = Some(ctk.clone());

Expand Down Expand Up @@ -182,11 +185,11 @@ pub struct EndpointInfo {

pub struct MDnsDiscovery {
daemon: ServiceDaemon,
sender: mpsc::Sender<EndpointInfo>,
sender: broadcast::Sender<EndpointInfo>,
}

impl MDnsDiscovery {
pub fn new(sender: mpsc::Sender<EndpointInfo>) -> Result<Self, anyhow::Error> {
pub fn new(sender: broadcast::Sender<EndpointInfo>) -> Result<Self, anyhow::Error> {
let daemon = ServiceDaemon::new()?;

Ok(Self { daemon, sender })
Expand Down Expand Up @@ -248,15 +251,15 @@ impl MDnsDiscovery {
present: Some(true),
};
info!("Resolved a new service: {:?}", ei);
let _ = self.sender.send(ei).await;
let _ = self.sender.send(ei);
}
}
ServiceEvent::ServiceRemoved(_, fullname) => {
info!("Remove a previous service: {}", fullname);
let _ = self.sender.send(EndpointInfo {
id: fullname,
..Default::default()
}).await;
});
}
ServiceEvent::SearchStarted(_) | ServiceEvent::SearchStopped(_) => {}
_ => {}
Expand Down
1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"dev": "cross-env RUST_BACKTRACE=1 concurrently -k \"tauri dev\" \"pnpm devtools\"",
"tauri": "tauri",
"deb:build": "tauri build -b deb,appimage",
"build": "tauri build",
"vite:dev": "vite dev",
Expand Down
42 changes: 41 additions & 1 deletion frontend/src-tauri/Cargo.lock

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

4 changes: 3 additions & 1 deletion frontend/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ tauri-build = { version = "2.0.0-beta", features = [] }

[dependencies]
anyhow = "1.0"
fern = { version = "0.6.2", features = ["colored"] }
humantime = "2.1.0"
log = "0.4"
notify-rust = "4.10.0"
open = "5.0"
Expand All @@ -25,9 +27,9 @@ tauri-plugin-autostart = "2.0.0-beta"
tauri-plugin-notification = "2.0.0-beta"
tauri-plugin-single-instance = "2.0.0-beta"
tauri-plugin-store = "2.0.0-beta"
time = "0.3.34"
tokio = { version = "1.25", features = ["macros", "rt", "rt-multi-thread", "net", "sync", "time", "io-util"] }
tokio-util = { version = "0.7", features = ["rt"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

[features]
# by default Tauri runs in production mode
Expand Down
94 changes: 94 additions & 0 deletions frontend/src-tauri/src/logger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use fern::colors::{Color, ColoredLevelConfig};
use tauri::{AppHandle, Manager};
use time::OffsetDateTime;

pub fn set_up_logging(app_handle: &AppHandle) -> Result<(), anyhow::Error> {
// Define default log level
let default_level = if cfg!(debug_assertions) {
log::LevelFilter::Trace
} else {
log::LevelFilter::Info
};

let colors = ColoredLevelConfig::new()
.error(Color::Red)
.warn(Color::Yellow)
.info(Color::Green)
.debug(Color::Blue)
.trace(Color::Cyan);

let dispatch = fern::Dispatch::new()
.format(move |out, message, record| {
out.finish(format_args!(
"\x1B[2m{date}\x1b[0m {level: >5} \x1B[2m{target}:\x1b[0m {message}",
date = humantime::format_rfc3339_seconds(SystemTime::now()),
target = record.target(),
level = colors.color(record.level()),
message = message,
));
})
.level(default_level)
.level_for("mdns_sd", log::LevelFilter::Error)
.level_for("polling", log::LevelFilter::Error)
.level_for("neli", log::LevelFilter::Error)
.level_for("bluez_async", log::LevelFilter::Error)
.level_for("bluer", log::LevelFilter::Error)
.level_for("async_io", log::LevelFilter::Error)
.level_for("polling", log::LevelFilter::Error)
.chain(std::io::stdout());

let app_name = &app_handle.package_info().name;
let path = app_handle.path().app_log_dir()?;
if !path.exists() {
std::fs::create_dir_all(&path)?;
}

let file_logger = fern::log_file(get_log_file_path(&path, app_name, 40000)?)?;

dispatch.chain(file_logger).apply()?;
debug!("Finished setting up logging! yay!");
Ok(())
}

fn get_log_file_path(
dir: &impl AsRef<Path>,
file_name: &str,
max_file_size: u128,
) -> Result<PathBuf, anyhow::Error> {
let path = dir.as_ref().join(format!("{file_name}.log"));

if path.exists() {
let log_size = File::open(&path)?.metadata()?.len() as u128;
if log_size > max_file_size {
let to = dir.as_ref().join(format!(
"{}_{}.log",
file_name,
OffsetDateTime::now_utc()
.format(
&time::format_description::parse(
"[year]-[month]-[day]_[hour]-[minute]-[second]"
)
.unwrap()
)
.unwrap(),
));

if to.is_file() {
let mut to_bak = to.clone();
to_bak.set_file_name(format!(
"{}.bak",
to_bak.file_name().unwrap().to_string_lossy()
));
std::fs::rename(&to, to_bak)?;
}

std::fs::rename(&path, to)?;
}
}

Ok(path)
}
Loading

0 comments on commit 1f7c986

Please sign in to comment.