Skip to content

Commit

Permalink
feat(logger): use env_logger and RUST_LOG for better control of loggi…
Browse files Browse the repository at this point in the history
…ng (#1618)

Co-authored-by: Darius Clark <dariusc93@users.noreply.github.com>
Co-authored-by: Sara Tavares <29093946+stavares843@users.noreply.github.com>
Co-authored-by: Sheldon McGee <sheldon@tooshel.com>
Co-authored-by: Luis E <35935591+luisecm@users.noreply.github.com>
  • Loading branch information
5 people authored Dec 15, 2023
1 parent af613e7 commit 2798914
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 127 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ target
kit/src/compiled_styles.css
ui/src/compiled_styles.css
.uplink
.env
ui/wix/*.zip
__MACOSX
27 changes: 27 additions & 0 deletions Cargo.lock

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

28 changes: 3 additions & 25 deletions common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,28 +30,6 @@ static_loader! {
};
}

// note that Trace and Trace2 are both LevelFilter::Trace. higher trace levels like Trace2
// enable tracing from modules besides Uplink
#[derive(clap::Subcommand, Debug)]
pub enum LogProfile {
/// normal operation
Normal,
/// print everything but tracing logs to the terminal
Debug,
/// print everything including tracing logs to the terminal
Trace,
/// like trace but include warp logs
TraceWarp,
/// trace dioxus
TraceDioxus,
/// Logs debug level from all crates to a file
DebugAll,
/// Logs trace level from all crates to a file
TraceAll,
/// maximum logging for blink
TraceBlink,
}

#[derive(Debug, Parser)]
#[clap(name = "")]
pub struct Args {
Expand All @@ -70,10 +48,10 @@ pub struct Args {
/// tells the app that it was installed via an installer, not built locally. Uplink will look for an `extra.zip` file based on
/// the platform-specific installer.
#[clap(long, default_value_t = false)]
production_mode: bool,
pub production_mode: bool,
/// configures log output
#[command(subcommand)]
pub profile: Option<LogProfile>,
#[clap(long, default_value_t = false)]
pub log_to_file: bool,
}

#[derive(Default, Debug, Clone, PartialEq)]
Expand Down
2 changes: 2 additions & 0 deletions ui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ reqwest = { workspace = true, default-features = false, features = [
"stream",
] }
log = { workspace = true }
env_logger = { version = "0.10"}
dotenv = {version = "0.15.0"}

[features]
default = ["dioxus-desktop/devtools"]
Expand Down
54 changes: 9 additions & 45 deletions ui/src/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::backtrace::Backtrace;
use super::*;

use crate::utils::auto_updater::DownloadState;
use ::log::Level;
use chrono::Local;
use common::state::ui::WindowMeta;
use common::state::State;
Expand Down Expand Up @@ -85,51 +84,16 @@ pub fn set_app_panic_hook() {
}))
}

pub fn configure_logger(profile: Option<LogProfile>) {
const BLINK_CRATE: &str = "warp-blink-wrtc";
let max_log_level = if let Some(profile) = profile {
match profile {
LogProfile::Debug => {
logger::allow_other_crates(Level::Debug, Some(&[BLINK_CRATE]));
logger::set_write_to_stdout(true);
LevelFilter::Debug
}
LogProfile::DebugAll => {
logger::allow_other_crates(Level::Debug, None);
logger::set_save_to_file(true);
LevelFilter::Debug
}
LogProfile::Trace => {
logger::set_write_to_stdout(true);
LevelFilter::Trace
}
LogProfile::TraceWarp => {
logger::allow_other_crates(Level::Trace, Some(&["warp", BLINK_CRATE]));
logger::set_write_to_stdout(true);
LevelFilter::Trace
}
LogProfile::TraceDioxus => {
logger::allow_other_crates(Level::Trace, Some(&["dioxus"]));
logger::set_write_to_stdout(true);
LevelFilter::Trace
}
LogProfile::TraceAll => {
logger::allow_other_crates(Level::Trace, None);
logger::set_save_to_file(true);
LevelFilter::Trace
}
LogProfile::TraceBlink => {
logger::allow_other_crates(Level::Trace, Some(&[BLINK_CRATE]));
logger::set_write_to_stdout(true);
LevelFilter::Debug
}
_ => LevelFilter::Debug,
}
} else {
LevelFilter::Debug
};
pub fn configure_logger(production_mode: bool, log_to_file: bool) {
if log_to_file {
logger::set_save_to_file(true);
}

if !production_mode {
logger::set_write_to_stdout(true);
}

logger::init_with_level(max_log_level).expect("failed to init logger");
logger::init().expect("failed to init logger");

::log::debug!("starting uplink");
}
Expand Down
7 changes: 4 additions & 3 deletions ui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use common::language::{get_local_text, get_local_text_with_args};
use common::notifications::{NotificationAction, NOTIFICATION_LISTENER};
use common::warp_runner::ui_adapter::MessageEvent;
use common::warp_runner::WarpEvent;
use common::{get_extras_dir, warp_runner, LogProfile, STATIC_ARGS, WARP_CMD_CH, WARP_EVENT_CH};
use common::{get_extras_dir, warp_runner, STATIC_ARGS, WARP_CMD_CH, WARP_EVENT_CH};

use dioxus::prelude::*;
use dioxus_desktop::tao::dpi::{LogicalPosition, PhysicalPosition};
Expand Down Expand Up @@ -60,7 +60,7 @@ use dioxus_desktop::wry::application::event::Event as WryEvent;
use dioxus_desktop::{use_wry_event_handler, DesktopService, PhysicalSize};
use tokio::sync::{mpsc, Mutex};
use tokio::time::{sleep, Duration};
use warp::logging::tracing::log::{self, LevelFilter};
use warp::logging::tracing::log::{self};

use muda::AboutMetadata;
use muda::Menu;
Expand Down Expand Up @@ -112,7 +112,8 @@ pub fn main_lib() {
bootstrap::platform_quirks();

// 2. configure logging via the cli
bootstrap::configure_logger(common::Args::parse().profile);
let args = common::Args::parse();
bootstrap::configure_logger(args.production_mode, args.log_to_file);

// 3. Make sure that if the app panics we can catch it
bootstrap::set_app_panic_hook();
Expand Down
84 changes: 30 additions & 54 deletions ui/src/logger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,17 @@
//! debug log back into a Log struct (would be easier for debug_logger but more difficult overall)
use colored::Colorize;
use log::{self, Level, LevelFilter, SetLoggerError};
use env_logger::Builder;
use log::{self, Level, SetLoggerError};
use once_cell::sync::Lazy;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::path::PathBuf;
use std::{collections::VecDeque, env};
use tokio::sync::mpsc;
use warp::sync::RwLock;

use chrono::{DateTime, Local};

use common::STATIC_ARGS;

static LOGGER: Lazy<RwLock<Logger>> = Lazy::new(|| RwLock::new(Logger::load()));
Expand Down Expand Up @@ -55,59 +54,41 @@ pub struct Logger {
subscribers: Vec<mpsc::UnboundedSender<Log>>,
max_logs: usize,
write_to_stdout: bool,

// minimum log level for 3rd party crates (warp, dioxus, etc)
max_level_3rd_party: Option<Level>,
whitelist: Option<HashSet<String>>,
}

// connects the `log` crate to the `Logger` singleton
struct LogGlue {
max_level: LevelFilter,
logger: env_logger::Logger,
}

impl LogGlue {
pub fn new(max_level: LevelFilter) -> Self {
Self { max_level }
}

fn log_external(&self, record: &log::Record) {
if LOGGER
.read()
.max_level_3rd_party
.as_ref()
.map(|max_level| &record.level() > max_level)
.unwrap_or(true)
{
return;
}

if let Some(whitelist) = LOGGER.read().whitelist.as_ref() {
let file_name = record.file();
let any_allowed = whitelist
.iter()
.any(|x| file_name.as_ref().map(|y| y.contains(x)).unwrap_or(false));
if !any_allowed {
return;
pub fn new() -> Self {
if !STATIC_ARGS.production_mode {
dotenv::dotenv().ok();

if env::var("RUST_LOG").is_err() {
env::set_var(
"RUST_LOG",
"uplink=debug,common=debug,kit=debug,warp_blink_wrtc=debug",
);
}
}

let msg = record.args();
LOGGER.write().log(record.level(), &msg.to_string());
// if in production mode, if RUST_LOG isn't set, the default should automatically get set to INFO.

let mut builder = Builder::from_env("RUST_LOG");
let logger = builder.build();
log::set_max_level(logger.filter());
Self { logger }
}
}

impl crate::log::Log for LogGlue {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= self.max_level
self.logger.enabled(metadata)
}

fn log(&self, record: &log::Record) {
// special path for other libraries
if record.file().map(|x| x.contains(".cargo")).unwrap_or(true) {
return self.log_external(record);
}

if self.enabled(record.metadata()) {
let msg = record.args();
LOGGER.write().log(record.level(), &msg.to_string());
Expand All @@ -128,8 +109,6 @@ impl Logger {
subscribers: vec![],
log_entries: VecDeque::new(),
max_logs: 128,
max_level_3rd_party: None,
whitelist: None,
}
}

Expand Down Expand Up @@ -225,11 +204,14 @@ impl Logger {
}
}
}

fn set_write_to_stdout(&mut self, b: bool) {
self.write_to_stdout = b;
}
}

pub fn init_with_level(level: LevelFilter) -> Result<(), SetLoggerError> {
log::set_max_level(level);
log::set_boxed_logger(Box::new(LogGlue::new(level)))?;
pub fn init() -> Result<(), SetLoggerError> {
log::set_boxed_logger(Box::new(LogGlue::new()))?;
Ok(())
}

Expand All @@ -255,22 +237,16 @@ pub fn subscribe() -> mpsc::UnboundedReceiver<Log> {
LOGGER.write().subscribe()
}

pub fn allow_other_crates(min_level: Level, whitelist: Option<&[&str]>) {
LOGGER.write().max_level_3rd_party.replace(min_level);
LOGGER.write().whitelist =
whitelist.map(|x| HashSet::from_iter(x.iter().map(|y| y.to_string())));
}

pub fn set_save_to_file(b: bool) {
LOGGER.write().set_save_to_file(b);
}

pub fn get_save_to_file() -> bool {
LOGGER.read().get_save_to_file()
pub fn set_write_to_stdout(b: bool) {
LOGGER.write().set_write_to_stdout(b);
}

pub fn set_write_to_stdout(b: bool) {
LOGGER.write().write_to_stdout = b;
pub fn get_save_to_file() -> bool {
LOGGER.read().get_save_to_file()
}

pub fn load_debug_log() -> Vec<Log> {
Expand Down

0 comments on commit 2798914

Please sign in to comment.