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

@@ -810,7 +810,7 @@ impl Frame {
#[doc(alias = "exit")]
#[doc(alias = "quit")]
pub fn close(&mut self) {
tracing::debug!("eframe::Frame::close called");
log::debug!("eframe::Frame::close called");
self.output.close = true;
}
@@ -1088,7 +1088,7 @@ pub fn get_value<T: serde::de::DeserializeOwned>(storage: &dyn Storage, key: &st
pub fn set_value<T: serde::Serialize>(storage: &mut dyn Storage, key: &str, value: &T) {
match ron::ser::to_string(value) {
Ok(string) => storage.set_string(key, string),
Err(err) => tracing::error!("eframe failed to encode data using ron: {}", err),
Err(err) => log::error!("eframe failed to encode data using ron: {}", err),
}
}

View File

@@ -201,13 +201,13 @@ pub fn run_native(
match renderer {
#[cfg(feature = "glow")]
Renderer::Glow => {
tracing::debug!("Using the glow renderer");
log::debug!("Using the glow renderer");
native::run::run_glow(app_name, native_options, app_creator)
}
#[cfg(feature = "wgpu")]
Renderer::Wgpu => {
tracing::debug!("Using the wgpu renderer");
log::debug!("Using the wgpu renderer");
native::run::run_wgpu(app_name, native_options, app_creator)
}
}

View File

@@ -425,12 +425,12 @@ impl EpiIntegration {
match event {
WindowEvent::CloseRequested => {
tracing::debug!("Received WindowEvent::CloseRequested");
log::debug!("Received WindowEvent::CloseRequested");
self.close = app.on_close_event();
tracing::debug!("App::on_close_event returned {}", self.close);
log::debug!("App::on_close_event returned {}", self.close);
}
WindowEvent::Destroyed => {
tracing::debug!("Received WindowEvent::Destroyed");
log::debug!("Received WindowEvent::Destroyed");
self.close = true;
}
WindowEvent::MouseInput {
@@ -483,7 +483,7 @@ impl EpiIntegration {
self.can_drag_window = false;
if app_output.close {
self.close = app.on_close_event();
tracing::debug!("App::on_close_event returned {}", self.close);
log::debug!("App::on_close_event returned {}", self.close);
}
self.frame.output.visible = app_output.visible; // this is handled by post_present
self.frame.output.screenshot_requested = app_output.screenshot_requested;

View File

@@ -26,7 +26,7 @@ impl FileStorage {
/// Store the state in this .ron file.
pub fn from_ron_filepath(ron_filepath: impl Into<PathBuf>) -> Self {
let ron_filepath: PathBuf = ron_filepath.into();
tracing::debug!("Loading app state from {:?}…", ron_filepath);
log::debug!("Loading app state from {:?}…", ron_filepath);
Self {
kv: read_ron(&ron_filepath).unwrap_or_default(),
ron_filepath,
@@ -40,7 +40,7 @@ impl FileStorage {
if let Some(proj_dirs) = directories_next::ProjectDirs::from("", "", app_name) {
let data_dir = proj_dirs.data_dir().to_path_buf();
if let Err(err) = std::fs::create_dir_all(&data_dir) {
tracing::warn!(
log::warn!(
"Saving disabled: Failed to create app path at {:?}: {}",
data_dir,
err
@@ -50,7 +50,7 @@ impl FileStorage {
Some(Self::from_ron_filepath(data_dir.join("app.ron")))
}
} else {
tracing::warn!("Saving disabled: Failed to find path to data_dir.");
log::warn!("Saving disabled: Failed to find path to data_dir.");
None
}
}
@@ -84,7 +84,7 @@ impl crate::Storage for FileStorage {
let file = std::fs::File::create(&file_path).unwrap();
let config = Default::default();
ron::ser::to_writer_pretty(file, &kv, config).unwrap();
tracing::trace!("Persisted to {:?}", file_path);
log::trace!("Persisted to {:?}", file_path);
});
self.last_save_join_handle = Some(join_handle);
@@ -104,7 +104,7 @@ where
match ron::de::from_reader(reader) {
Ok(value) => Some(value),
Err(err) => {
tracing::warn!("Failed to parse RON: {}", err);
log::warn!("Failed to parse RON: {}", err);
None
}
}

View File

@@ -115,7 +115,7 @@ fn run_and_return(
) -> Result<()> {
use winit::platform::run_return::EventLoopExtRunReturn as _;
tracing::debug!("Entering the winit event loop (run_return)…");
log::debug!("Entering the winit event loop (run_return)…");
let mut next_repaint_time = Instant::now();
@@ -126,7 +126,7 @@ fn run_and_return(
winit::event::Event::LoopDestroyed => {
// On Mac, Cmd-Q we get here and then `run_return` doesn't return (despite its name),
// so we need to save state now:
tracing::debug!("Received Event::LoopDestroyed - saving app state…");
log::debug!("Received Event::LoopDestroyed - saving app state…");
winit_app.save_and_destroy();
*control_flow = ControlFlow::Exit;
return;
@@ -161,7 +161,7 @@ fn run_and_return(
event => match winit_app.on_event(event_loop, event) {
Ok(event_result) => event_result,
Err(err) => {
tracing::error!("Exiting because of error: {err:?} on event {event:?}");
log::error!("Exiting because of error: {err:?} on event {event:?}");
returned_result = Err(err);
EventResult::Exit
}
@@ -171,7 +171,7 @@ fn run_and_return(
match event_result {
EventResult::Wait => {}
EventResult::RepaintNow => {
tracing::trace!("Repaint caused by winit::Event: {:?}", event);
log::trace!("Repaint caused by winit::Event: {:?}", event);
if cfg!(windows) {
// Fix flickering on Windows, see https://github.com/emilk/egui/pull/2280
next_repaint_time = Instant::now() + Duration::from_secs(1_000_000_000);
@@ -182,14 +182,14 @@ fn run_and_return(
}
}
EventResult::RepaintNext => {
tracing::trace!("Repaint caused by winit::Event: {:?}", event);
log::trace!("Repaint caused by winit::Event: {:?}", event);
next_repaint_time = Instant::now();
}
EventResult::RepaintAt(repaint_time) => {
next_repaint_time = next_repaint_time.min(repaint_time);
}
EventResult::Exit => {
tracing::debug!("Asking to exit event loop…");
log::debug!("Asking to exit event loop…");
winit_app.save_and_destroy();
*control_flow = ControlFlow::Exit;
return;
@@ -210,7 +210,7 @@ fn run_and_return(
}
});
tracing::debug!("eframe window closed");
log::debug!("eframe window closed");
drop(winit_app);
@@ -224,14 +224,14 @@ fn run_and_return(
}
fn run_and_exit(event_loop: EventLoop<UserEvent>, mut winit_app: impl WinitApp + 'static) -> ! {
tracing::debug!("Entering the winit event loop (run)…");
log::debug!("Entering the winit event loop (run)…");
let mut next_repaint_time = Instant::now();
event_loop.run(move |event, event_loop, control_flow| {
let event_result = match event {
winit::event::Event::LoopDestroyed => {
tracing::debug!("Received Event::LoopDestroyed");
log::debug!("Received Event::LoopDestroyed");
EventResult::Exit
}
@@ -279,7 +279,7 @@ fn run_and_exit(event_loop: EventLoop<UserEvent>, mut winit_app: impl WinitApp +
next_repaint_time = next_repaint_time.min(repaint_time);
}
EventResult::Exit => {
tracing::debug!("Quitting - saving app state…");
log::debug!("Quitting - saving app state…");
winit_app.save_and_destroy();
#[allow(clippy::exit)]
std::process::exit(0);
@@ -410,7 +410,7 @@ mod glow_integration {
config_template_builder
};
tracing::debug!(
log::debug!(
"trying to create glutin Display with config: {:?}",
&config_template_builder
);
@@ -426,7 +426,7 @@ mod glow_integration {
let config = config_iterator.next().expect(
"failed to find a matching configuration for creating glutin config",
);
tracing::debug!(
log::debug!(
"using the first config from config picker closure. config: {:?}",
&config
);
@@ -436,13 +436,13 @@ mod glow_integration {
.map_err(|e| crate::Error::NoGlutinConfigs(config_template_builder.build(), e))?;
let gl_display = gl_config.display();
tracing::debug!(
log::debug!(
"successfully created GL Display with version: {} and supported features: {:?}",
gl_display.version_string(),
gl_display.supported_features()
);
let raw_window_handle = window.as_ref().map(|w| w.raw_window_handle());
tracing::debug!(
log::debug!(
"creating gl context using raw window handle: {:?}",
raw_window_handle
);
@@ -459,8 +459,8 @@ mod glow_integration {
{
Ok(it) => it,
Err(err) => {
tracing::warn!("failed to create context using default context attributes {context_attributes:?} due to error: {err}");
tracing::debug!("retrying with fallback context attributes: {fallback_context_attributes:?}");
log::warn!("failed to create context using default context attributes {context_attributes:?} due to error: {err}");
log::debug!("retrying with fallback context attributes: {fallback_context_attributes:?}");
gl_config
.display()
.create_context(&gl_config, &fallback_context_attributes)?
@@ -494,15 +494,13 @@ mod glow_integration {
#[allow(unsafe_code)]
fn on_resume(&mut self, event_loop: &EventLoopWindowTarget<UserEvent>) -> Result<()> {
if self.gl_surface.is_some() {
tracing::warn!(
"on_resume called even thought we already have a surface. early return"
);
log::warn!("on_resume called even thought we already have a surface. early return");
return Ok(());
}
tracing::debug!("running on_resume fn.");
log::debug!("running on_resume fn.");
// make sure we have a window or create one.
let window = self.window.take().unwrap_or_else(|| {
tracing::debug!("window doesn't exist yet. creating one now with finalize_window");
log::debug!("window doesn't exist yet. creating one now with finalize_window");
glutin_winit::finalize_window(event_loop, self.builder.clone(), &self.gl_config)
.expect("failed to finalize glutin window")
});
@@ -513,7 +511,7 @@ mod glow_integration {
let surface_attributes =
glutin::surface::SurfaceAttributesBuilder::<glutin::surface::WindowSurface>::new()
.build(window.raw_window_handle(), width, height);
tracing::debug!(
log::debug!(
"creating surface with attributes: {:?}",
&surface_attributes
);
@@ -523,7 +521,7 @@ mod glow_integration {
.display()
.create_window_surface(&self.gl_config, &surface_attributes)?
};
tracing::debug!("surface created successfully: {gl_surface:?}.making context current");
log::debug!("surface created successfully: {gl_surface:?}.making context current");
// make surface and context current.
let not_current_gl_context = self
.not_current_gl_context
@@ -531,9 +529,9 @@ mod glow_integration {
.expect("failed to get not current context after resume event. impossible!");
let current_gl_context = not_current_gl_context.make_current(&gl_surface)?;
// try setting swap interval. but its not absolutely necessary, so don't panic on failure.
tracing::debug!("made context current. setting swap interval for surface");
log::debug!("made context current. setting swap interval for surface");
if let Err(e) = gl_surface.set_swap_interval(&current_gl_context, self.swap_interval) {
tracing::error!("failed to set swap interval due to error: {e:?}");
log::error!("failed to set swap interval due to error: {e:?}");
}
// we will reach this point only once in most platforms except android.
// create window/surface/make context current once and just use them forever.
@@ -545,16 +543,14 @@ mod glow_integration {
/// only applies for android. but we basically drop surface + window and make context not current
fn on_suspend(&mut self) -> Result<()> {
tracing::debug!("received suspend event. dropping window and surface");
log::debug!("received suspend event. dropping window and surface");
self.gl_surface.take();
self.window.take();
if let Some(current) = self.current_gl_context.take() {
tracing::debug!("context is current, so making it non-current");
log::debug!("context is current, so making it non-current");
self.not_current_gl_context = Some(current.make_not_current()?);
} else {
tracing::debug!(
"context is already not current??? could be duplicate suspend event"
);
log::debug!("context is already not current??? could be duplicate suspend event");
}
Ok(())
}
@@ -952,7 +948,7 @@ mod glow_integration {
winit::event::WindowEvent::CloseRequested
if running.integration.should_close() =>
{
tracing::debug!("Received WindowEvent::CloseRequested");
log::debug!("Received WindowEvent::CloseRequested");
return Ok(EventResult::Exit);
}
_ => {}
@@ -1375,7 +1371,7 @@ mod wgpu_integration {
winit::event::WindowEvent::CloseRequested
if running.integration.should_close() =>
{
tracing::debug!("Received WindowEvent::CloseRequested");
log::debug!("Received WindowEvent::CloseRequested");
return Ok(EventResult::Exit);
}
_ => {}

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,