1
0
mirror of https://github.com/emilk/egui.git synced 2026-08-31 22:00:03 -04:00

Replace tracing with log (#2928)

* Replace tracing crate with log

It's just so much simpler to use

* Add `bacon wasm` job

* eframe: add a WebLogger for piping log events to the web console
This commit is contained in:
Emil Ernerfeldt
2023-04-18 21:11:26 +02:00
committed by GitHub
parent 0f9e1a3526
commit 9c9a54ce36
48 changed files with 477 additions and 291 deletions

View File

@@ -187,7 +187,7 @@ pub struct AppRunner {
impl Drop for AppRunner {
fn drop(&mut self) {
tracing::debug!("AppRunner has fully dropped");
log::debug!("AppRunner has fully dropped");
}
}
@@ -336,10 +336,10 @@ impl AppRunner {
let is_destroyed_already = self.is_destroyed.fetch();
if is_destroyed_already {
tracing::warn!("App was destroyed already");
log::warn!("App was destroyed already");
Ok(())
} else {
tracing::debug!("Destroying");
log::debug!("Destroying");
for x in self.events_to_unsubscribe.drain(..) {
x.unsubscribe()?;
}
@@ -536,7 +536,7 @@ pub async fn start(
app_creator: epi::AppCreator,
) -> Result<AppRunnerRef, JsValue> {
#[cfg(not(web_sys_unstable_apis))]
tracing::warn!(
log::warn!(
"eframe compiled without RUSTFLAGS='--cfg=web_sys_unstable_apis'. Copying text won't work."
);
let follow_system_theme = web_options.follow_system_theme;
@@ -572,7 +572,7 @@ fn start_runner(app_runner: AppRunner, follow_system_theme: bool) -> Result<AppR
runner_container.runner.lock().events_to_unsubscribe = runner_container.events;
std::panic::set_hook(Box::new(move |panic_info| {
tracing::info!("egui disabled all event handlers due to panic");
log::info!("egui disabled all event handlers due to panic");
runner_container.panicked.store(true, SeqCst);
// Propagate panic info to the previously registered panic hook

View File

@@ -67,7 +67,7 @@ pub fn install_document_events(runner_container: &mut AppRunnerContainer) -> Res
runner_lock.input.on_web_page_focus_change(has_focus);
runner_lock.egui_ctx().request_repaint();
// tracing::debug!("{event_name:?}");
// log::debug!("{event_name:?}");
};
runner_container.add_event_listener(&document, event_name, closure)?;
@@ -135,7 +135,7 @@ pub fn install_document_events(runner_container: &mut AppRunnerContainer) -> Res
false
};
// tracing::debug!(
// log::debug!(
// "On key-down {:?}, egui_wants_keyboard: {}, prevent_default: {}",
// event.key().as_str(),
// egui_wants_keyboard,
@@ -282,7 +282,7 @@ pub fn install_canvas_events(runner_container: &mut AppRunnerContainer) -> Resul
mut _runner_lock: egui::mutex::MutexGuard<'_, AppRunner>| {
event.prevent_default();
// event.stop_propagation();
// tracing::debug!("Preventing event {event_name:?}");
// log::debug!("Preventing event {event_name:?}");
};
runner_container.add_event_listener(&canvas, event_name, closure)?;
@@ -564,7 +564,7 @@ pub fn install_canvas_events(runner_container: &mut AppRunnerContainer) -> Resul
let last_modified = std::time::UNIX_EPOCH
+ std::time::Duration::from_millis(file.last_modified() as u64);
tracing::debug!("Loading {:?} ({} bytes)…", name, file.size());
log::debug!("Loading {:?} ({} bytes)…", name, file.size());
let future = wasm_bindgen_futures::JsFuture::from(file.array_buffer());
@@ -573,11 +573,7 @@ pub fn install_canvas_events(runner_container: &mut AppRunnerContainer) -> Resul
match future.await {
Ok(array_buffer) => {
let bytes = js_sys::Uint8Array::new(&array_buffer).to_vec();
tracing::debug!(
"Loaded {:?} ({} bytes).",
name,
bytes.len()
);
log::debug!("Loaded {:?} ({} bytes).", name, bytes.len());
// Re-lock the mutex on the other side of the await point
let mut runner_lock = runner_ref.lock();
@@ -592,7 +588,7 @@ pub fn install_canvas_events(runner_container: &mut AppRunnerContainer) -> Resul
runner_lock.needs_repaint.repaint_asap();
}
Err(err) => {
tracing::error!("Failed to read file: {:?}", err);
log::error!("Failed to read file: {:?}", err);
}
}
};

View File

@@ -8,6 +8,9 @@ mod input;
pub mod screen_reader;
pub mod storage;
mod text_agent;
mod web_logger;
pub use web_logger::WebLogger;
#[cfg(not(any(feature = "glow", feature = "wgpu")))]
compile_error!("You must enable either the 'glow' or 'wgpu' feature");
@@ -135,7 +138,7 @@ pub fn resize_canvas_to_screen_size(canvas_id: &str, max_size_points: egui::Vec2
};
if width <= 0 || height <= 0 {
tracing::error!("egui canvas parent size is {}x{}. Try adding `html, body {{ height: 100%; width: 100% }}` to your CSS!", width, height);
log::error!("egui canvas parent size is {}x{}. Try adding `html, body {{ height: 100%; width: 100% }}` to your CSS!", width, height);
}
let pixels_per_point = native_pixels_per_point();
@@ -192,7 +195,7 @@ pub fn set_clipboard_text(s: &str) {
let future = wasm_bindgen_futures::JsFuture::from(promise);
let future = async move {
if let Err(err) = future.await {
tracing::error!("Copy/cut action denied: {:?}", err);
log::error!("Copy/cut action denied: {:?}", err);
}
};
wasm_bindgen_futures::spawn_local(future);

View File

@@ -16,11 +16,11 @@ impl Default for ScreenReader {
fn default() -> Self {
let tts = match tts::Tts::default() {
Ok(screen_reader) => {
tracing::debug!("Initialized screen reader.");
log::debug!("Initialized screen reader.");
Some(screen_reader)
}
Err(err) => {
tracing::warn!("Failed to load screen reader: {}", err);
log::warn!("Failed to load screen reader: {}", err);
None
}
};
@@ -39,10 +39,10 @@ impl ScreenReader {
return;
}
if let Some(tts) = &mut self.tts {
tracing::debug!("Speaking: {:?}", text);
log::debug!("Speaking: {:?}", text);
let interrupt = true;
if let Err(err) = tts.speak(text, interrupt) {
tracing::warn!("Failed to read: {}", err);
log::warn!("Failed to read: {}", err);
}
}
}

View File

@@ -18,7 +18,7 @@ pub fn load_memory(ctx: &egui::Context) {
ctx.memory_mut(|m| *m = memory);
}
Err(err) => {
tracing::error!("Failed to parse memory RON: {}", err);
log::error!("Failed to parse memory RON: {}", err);
}
}
}
@@ -34,7 +34,7 @@ pub fn save_memory(ctx: &egui::Context) {
local_storage_set("egui_memory_ron", &ron);
}
Err(err) => {
tracing::error!("Failed to serialize memory as RON: {}", err);
log::error!("Failed to serialize memory as RON: {}", err);
}
}
}

View File

@@ -0,0 +1,110 @@
/// Implements [`log::Log`] to log messages to `console.log`, `console.warn`, etc.
pub struct WebLogger {
filter: log::LevelFilter,
}
impl WebLogger {
/// Pipe all [`log`] events to the web console.
pub fn init(filter: log::LevelFilter) -> Result<(), log::SetLoggerError> {
log::set_max_level(filter);
log::set_boxed_logger(Box::new(WebLogger::new(filter)))
}
pub fn new(filter: log::LevelFilter) -> Self {
Self { filter }
}
}
impl log::Log for WebLogger {
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
metadata.level() <= self.filter
}
fn log(&self, record: &log::Record<'_>) {
if !self.enabled(record.metadata()) {
return;
}
let msg = if let (Some(file), Some(line)) = (record.file(), record.line()) {
let file = shorten_file_path(file);
format!("[{}] {file}:{line}: {}", record.target(), record.args())
} else {
format!("[{}] {}", record.target(), record.args())
};
match record.level() {
log::Level::Trace => console::trace(&msg),
log::Level::Debug => console::debug(&msg),
log::Level::Info => console::info(&msg),
log::Level::Warn => console::warn(&msg),
log::Level::Error => console::error(&msg),
}
}
fn flush(&self) {}
}
/// js-bindings for console.log, console.warn, etc
mod console {
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
/// `console.trace`
#[wasm_bindgen(js_namespace = console)]
pub fn trace(s: &str);
/// `console.debug`
#[wasm_bindgen(js_namespace = console)]
pub fn debug(s: &str);
/// `console.info`
#[wasm_bindgen(js_namespace = console)]
pub fn info(s: &str);
/// `console.warn`
#[wasm_bindgen(js_namespace = console)]
pub fn warn(s: &str);
/// `console.error`
#[wasm_bindgen(js_namespace = console)]
pub fn error(s: &str);
}
}
/// Shorten a path to a Rust source file.
///
/// Example input:
/// * `/Users/emilk/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.24.1/src/runtime/runtime.rs`
/// * `crates/rerun/src/main.rs`
/// * `/rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/ops/function.rs`
///
/// Example output:
/// * `tokio-1.24.1/src/runtime/runtime.rs`
/// * `rerun/src/main.rs`
/// * `core/src/ops/function.rs`
#[allow(dead_code)] // only used on web and in tests
fn shorten_file_path(file_path: &str) -> &str {
if let Some(i) = file_path.rfind("/src/") {
if let Some(prev_slash) = file_path[..i].rfind('/') {
&file_path[prev_slash + 1..]
} else {
file_path
}
} else {
file_path
}
}
#[test]
fn test_shorten_file_path() {
for (before, after) in [
("/Users/emilk/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.24.1/src/runtime/runtime.rs", "tokio-1.24.1/src/runtime/runtime.rs"),
("crates/rerun/src/main.rs", "rerun/src/main.rs"),
("/rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/ops/function.rs", "core/src/ops/function.rs"),
("/weird/path/file.rs", "/weird/path/file.rs"),
]
{
assert_eq!(shorten_file_path(before), after);
}
}

View File

@@ -106,14 +106,14 @@ fn init_webgl1(canvas: &HtmlCanvasElement) -> Option<(glow::Context, &'static st
.expect("Failed to query about WebGL2 context");
let gl1_ctx = gl1_ctx?;
tracing::debug!("WebGL1 selected.");
log::debug!("WebGL1 selected.");
let gl1_ctx = gl1_ctx
.dyn_into::<web_sys::WebGlRenderingContext>()
.unwrap();
let shader_prefix = if webgl1_requires_brightening(&gl1_ctx) {
tracing::debug!("Enabling webkitGTK brightening workaround.");
log::debug!("Enabling webkitGTK brightening workaround.");
"#define APPLY_BRIGHTENING_GAMMA"
} else {
""
@@ -130,7 +130,7 @@ fn init_webgl2(canvas: &HtmlCanvasElement) -> Option<(glow::Context, &'static st
.expect("Failed to query about WebGL2 context");
let gl2_ctx = gl2_ctx?;
tracing::debug!("WebGL2 selected.");
log::debug!("WebGL2 selected.");
let gl2_ctx = gl2_ctx
.dyn_into::<web_sys::WebGl2RenderingContext>()

View File

@@ -57,7 +57,7 @@ impl WebPainterWgpu {
#[allow(unused)] // only used if `wgpu` is the only active feature.
pub async fn new(canvas_id: &str, options: &WebOptions) -> Result<Self, String> {
tracing::debug!("Creating wgpu painter");
log::debug!("Creating wgpu painter");
let canvas = super::canvas_element_or_die(canvas_id);
@@ -108,7 +108,7 @@ impl WebPainterWgpu {
view_formats: vec![target_format],
};
tracing::debug!("wgpu painter initialized.");
log::debug!("wgpu painter initialized.");
Ok(Self {
canvas,