Skip to content

Commit

Permalink
Replace log with tracing
Browse files Browse the repository at this point in the history
Tracing is a modern replacement for the log crate that allows for
annotating log messages with the function that they come from.

Signed-off-by: John Nunley <[email protected]>
Closes: #3482
  • Loading branch information
notgull authored and kchibisov committed Mar 1, 2024
1 parent 9617269 commit 9443476
Show file tree
Hide file tree
Showing 44 changed files with 249 additions and 68 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ Unreleased` header.
- **Breaking:** Changed the signature of `EventLoop::with_user_event` to return a builder.
- **Breaking:** Removed `EventLoopBuilder::with_user_event`, the functionality is now available in `EventLoop::with_user_event`.
- Add `Window::default_attributes` to get default `WindowAttributes`.
- `log` has been replaced with `tracing`. The old behavior can be emulated by setting the `log` feature on the `tracing` crate.

# 0.29.12

Expand Down
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,17 +64,18 @@ cfg_aliases = "0.2.0"
[dependencies]
bitflags = "2"
cursor-icon = "1.1.0"
log = "0.4"
rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true }
rwh_05 = { package = "raw-window-handle", version = "0.5.2", features = ["std"], optional = true }
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"], optional = true }
serde = { workspace = true, optional = true }
smol_str = "0.2.0"
dpi = { path = "dpi" }
tracing = { version = "0.1.40", default_features = false }

[dev-dependencies]
image = { version = "0.24.0", default-features = false, features = ["png"] }
simple_logger = { version = "4.2.0", default_features = false }
tracing = { version = "0.1.40", default_features = false, features = ["log"] }
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
winit = { path = ".", features = ["rwh_05"] }

[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies]
Expand Down
3 changes: 1 addition & 2 deletions examples/control_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use std::time;
#[cfg(web_platform)]
use web_time as time;

use simple_logger::SimpleLogger;
use winit::{
event::{ElementState, Event, KeyEvent, WindowEvent},
event_loop::{ControlFlow, EventLoop},
Expand All @@ -28,7 +27,7 @@ const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);

fn main() -> Result<(), impl std::error::Error> {
SimpleLogger::new().init().unwrap();
tracing_subscriber::fmt::init();

println!("Press '1' to switch to Wait mode.");
println!("Press '2' to switch to WaitUntil mode.");
Expand Down
3 changes: 1 addition & 2 deletions examples/pump_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
fn main() -> std::process::ExitCode {
use std::{process::ExitCode, thread::sleep, time::Duration};

use simple_logger::SimpleLogger;
use winit::{
event::{Event, WindowEvent},
event_loop::EventLoop,
Expand All @@ -24,7 +23,7 @@ fn main() -> std::process::ExitCode {

let mut event_loop = EventLoop::new().unwrap();

SimpleLogger::new().init().unwrap();
tracing_subscriber::fmt::init();

let mut window = None;

Expand Down
4 changes: 1 addition & 3 deletions examples/run_on_demand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
fn main() -> Result<(), impl std::error::Error> {
use std::time::Duration;

use simple_logger::SimpleLogger;

use winit::{
error::EventLoopError,
event::{Event, WindowEvent},
Expand All @@ -24,7 +22,7 @@ fn main() -> Result<(), impl std::error::Error> {
window: Option<Window>,
}

SimpleLogger::new().init().unwrap();
tracing_subscriber::fmt::init();
let mut event_loop = EventLoop::new().unwrap();

fn run_app(event_loop: &mut EventLoop<()>, idx: usize) -> Result<(), EventLoopError> {
Expand Down
4 changes: 1 addition & 3 deletions examples/x11_embed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ use std::error::Error;

#[cfg(x11_platform)]
fn main() -> Result<(), Box<dyn Error>> {
use simple_logger::SimpleLogger;

use winit::{
event::{Event, WindowEvent},
event_loop::EventLoop,
Expand All @@ -21,7 +19,7 @@ fn main() -> Result<(), Box<dyn Error>> {
.ok_or("Expected a 32-bit X11 window ID as the first argument.")?
.parse::<u32>()?;

SimpleLogger::new().init().unwrap();
tracing_subscriber::fmt::init();
let event_loop = EventLoop::new()?;

let mut window = None;
Expand Down
9 changes: 9 additions & 0 deletions src/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,15 @@ impl CustomCursor {
hotspot_x: u16,
hotspot_y: u16,
) -> Result<CustomCursorSource, BadImage> {
let _span = tracing::debug_span!(
"winit::Cursor::from_rgba",
width,
height,
hotspot_x,
hotspot_y
)
.entered();

Ok(CustomCursorSource {
inner: PlatformCustomCursorSource::from_rgba(
rgba.into(),
Expand Down
38 changes: 38 additions & 0 deletions src/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ impl<T> EventLoopBuilder<T> {
)]
#[inline]
pub fn build(&mut self) -> Result<EventLoop<T>, EventLoopError> {
let _span = tracing::debug_span!("winit::EventLoopBuilder::build").entered();

if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
return Err(EventLoopError::RecreationAttempt);
}
Expand Down Expand Up @@ -248,6 +250,8 @@ impl<T> EventLoop<T> {
where
F: FnMut(Event<T>, &ActiveEventLoop),
{
let _span = tracing::debug_span!("winit::EventLoop::run").entered();

self.event_loop.run(event_handler)
}

Expand All @@ -274,6 +278,12 @@ impl<T> EventLoop<T> {
///
/// [`DeviceEvent`]: crate::event::DeviceEvent
pub fn listen_device_events(&self, allowed: DeviceEvents) {
let _span = tracing::debug_span!(
"winit::EventLoop::listen_device_events",
allowed = ?allowed
)
.entered();

self.event_loop
.window_target()
.p
Expand All @@ -295,6 +305,12 @@ impl<T> EventLoop<T> {
#[deprecated = "use `ActiveEventLoop::create_window` instead"]
#[inline]
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
let _span = tracing::debug_span!(
"winit::EventLoop::create_window",
window_attributes = ?window_attributes
)
.entered();

let window =
platform_impl::Window::new(&self.event_loop.window_target().p, window_attributes)?;
Ok(Window { window })
Expand Down Expand Up @@ -363,18 +379,28 @@ impl ActiveEventLoop {
/// see the web platform module for more information.
#[inline]
pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> {
let _span = tracing::debug_span!(
"winit::ActiveEventLoop::create_window",
window_attributes = ?window_attributes
)
.entered();

let window = platform_impl::Window::new(&self.p, window_attributes)?;
Ok(Window { window })
}

/// Create custom cursor.
pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor {
let _span = tracing::debug_span!("winit::ActiveEventLoop::create_custom_cursor",).entered();

self.p.create_custom_cursor(custom_cursor)
}

/// Returns the list of all the monitors available on the system.
#[inline]
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
let _span = tracing::debug_span!("winit::ActiveEventLoop::available_monitors",).entered();

#[allow(clippy::useless_conversion)] // false positive on some platforms
self.p
.available_monitors()
Expand All @@ -391,6 +417,8 @@ impl ActiveEventLoop {
/// **Wayland / Web:** Always returns `None`.
#[inline]
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
let _span = tracing::debug_span!("winit::ActiveEventLoop::primary_monitor",).entered();

self.p
.primary_monitor()
.map(|inner| MonitorHandle { inner })
Expand All @@ -408,6 +436,12 @@ impl ActiveEventLoop {
///
/// [`DeviceEvent`]: crate::event::DeviceEvent
pub fn listen_device_events(&self, allowed: DeviceEvents) {
let _span = tracing::debug_span!(
"winit::ActiveEventLoop::listen_device_events",
allowed = ?allowed
)
.entered();

self.p.listen_device_events(allowed);
}

Expand All @@ -425,6 +459,8 @@ impl ActiveEventLoop {
///
/// See [`LoopExiting`](Event::LoopExiting).
pub fn exit(&self) {
let _span = tracing::debug_span!("winit::ActiveEventLoop::exit",).entered();

self.p.exit()
}

Expand Down Expand Up @@ -530,6 +566,8 @@ impl<T: 'static> EventLoopProxy<T> {
///
/// [`UserEvent(event)`]: Event::UserEvent
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
let _span = tracing::debug_span!("winit::EventLoopProxy::send_event",).entered();

self.event_loop_proxy.send_event(event)
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/icon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ impl Icon {
/// The length of `rgba` must be divisible by 4, and `width * height` must equal
/// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
let _span = tracing::debug_span!("winit::Icon::from_rgba", width, height).entered();

Ok(Icon {
inner: PlatformIcon::from_rgba(rgba, width, height)?,
})
Expand Down
6 changes: 3 additions & 3 deletions src/platform_impl/android/keycodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ pub fn character_map_and_combine_key(
let key_map = match app.device_key_character_map(device_id) {
Ok(key_map) => key_map,
Err(err) => {
log::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
tracing::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
return None;
}
};
Expand All @@ -188,7 +188,7 @@ pub fn character_map_and_combine_key(
Ok(Some(key)) => Some(key),
Ok(None) => None,
Err(err) => {
log::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
tracing::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
None
}
}
Expand All @@ -213,7 +213,7 @@ pub fn character_map_and_combine_key(
None
}
Err(err) => {
log::warn!("KeyEvent: Failed to get key map character: {err:?}");
tracing::warn!("KeyEvent: Failed to get key map character: {err:?}");
*combining_accent = None;
None
}
Expand Down
6 changes: 3 additions & 3 deletions src/platform_impl/android/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use android_activity::input::{InputEvent, KeyAction, Keycode, MotionAction};
use android_activity::{
AndroidApp, AndroidAppWaker, ConfigurationRef, InputStatus, MainEvent, Rect,
};
use log::{debug, trace, warn};
use tracing::{debug, trace, warn};

use crate::{
cursor::Cursor,
Expand Down Expand Up @@ -330,7 +330,7 @@ impl<T: 'static> EventLoop<T> {
}
},
Err(err) => {
log::warn!("Failed to get input events iterator: {err:?}");
tracing::warn!("Failed to get input events iterator: {err:?}");
}
}

Expand Down Expand Up @@ -1014,7 +1014,7 @@ impl Window {
if let Some(native_window) = self.app.native_window().as_ref() {
native_window.raw_window_handle()
} else {
log::error!("Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events.");
tracing::error!("Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events.");
Err(rwh_06::HandleError::Unavailable)
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/platform_impl/ios/app_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -622,9 +622,9 @@ pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(
match wrapper {
EventWrapper::StaticEvent(event) => {
if !processing_redraws && event.is_redraw() {
log::info!("processing `RedrawRequested` during the main event loop");
tracing::info!("processing `RedrawRequested` during the main event loop");
} else if processing_redraws && !event.is_redraw() {
log::warn!(
tracing::warn!(
"processing non `RedrawRequested` event after the main event loop: {:#?}",
event
);
Expand Down Expand Up @@ -676,9 +676,9 @@ pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(
match wrapper {
EventWrapper::StaticEvent(event) => {
if !processing_redraws && event.is_redraw() {
log::info!("processing `RedrawRequested` during the main event loop");
tracing::info!("processing `RedrawRequested` during the main event loop");
} else if processing_redraws && !event.is_redraw() {
log::warn!(
tracing::warn!(
"processing non-`RedrawRequested` event after the main event loop: {:#?}",
event
);
Expand Down Expand Up @@ -911,7 +911,7 @@ macro_rules! os_capabilities {
impl OSCapabilities {$(
$(#[$attr])*
pub fn $error_name(&self, extra_msg: &str) {
log::warn!(
tracing::warn!(
concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"),
$major, $minor, self.os_version.majorVersion, self.os_version.minorVersion, self.os_version.patchVersion,
extra_msg
Expand Down
2 changes: 1 addition & 1 deletion src/platform_impl/ios/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl ActiveEventLoop {
pub(crate) fn exit(&self) {
// https://developer.apple.com/library/archive/qa/qa1561/_index.html
// it is not possible to quit an iOS app gracefully and programmatically
log::warn!("`ControlFlow::Exit` ignored on iOS");
tracing::warn!("`ControlFlow::Exit` ignored on iOS");
}

pub(crate) fn exiting(&self) -> bool {
Expand Down
2 changes: 1 addition & 1 deletion src/platform_impl/ios/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
use std::collections::VecDeque;

use icrate::Foundation::{CGFloat, CGPoint, CGRect, CGSize, MainThreadBound, MainThreadMarker};
use log::{debug, warn};
use objc2::rc::Id;
use objc2::runtime::{AnyObject, NSObject};
use objc2::{class, declare_class, msg_send, msg_send_id, mutability, ClassType, DeclaredClass};
use tracing::{debug, warn};

use super::app_state::EventWrapper;
use super::uikit::{
Expand Down
4 changes: 2 additions & 2 deletions src/platform_impl/linux/common/xkb/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ use std::ptr::{self, NonNull};
use std::sync::atomic::{AtomicBool, Ordering};

use crate::utils::Lazy;
use log::warn;
use smol_str::SmolStr;
#[cfg(wayland_platform)]
use std::os::unix::io::OwnedFd;
use tracing::warn;
use xkbcommon_dl::{
self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle,
xkbcommon_handle, XkbCommon, XkbCommonCompose,
Expand Down Expand Up @@ -451,7 +451,7 @@ fn byte_slice_to_smol_str(bytes: &[u8]) -> Option<SmolStr> {
std::str::from_utf8(bytes)
.map(SmolStr::new)
.map_err(|e| {
log::warn!(
tracing::warn!(
"UTF-8 received from libxkbcommon ({:?}) was invalid: {e}",
bytes
)
Expand Down
2 changes: 1 addition & 1 deletion src/platform_impl/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ unsafe extern "C" fn x_error_callback(

// Don't log error.
if !error_handled {
log::error!("X11 error: {:#?}", error);
tracing::error!("X11 error: {:#?}", error);
// XXX only update the error, if it wasn't handled by any of the hooks.
*xconn.latest_error.lock().unwrap() = Some(error);
}
Expand Down
2 changes: 1 addition & 1 deletion src/platform_impl/linux/wayland/event_loop/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ impl<T: 'static> EventLoop<T> {
};

self.event_loop.dispatch(timeout, state).map_err(|error| {
log::error!("Error dispatching event loop: {}", error);
tracing::error!("Error dispatching event loop: {}", error);
error.into()
})
}
Expand Down
2 changes: 1 addition & 1 deletion src/platform_impl/linux/wayland/seat/keyboard/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::time::Duration;

use calloop::timer::{TimeoutAction, Timer};
use calloop::{LoopHandle, RegistrationToken};
use log::warn;
use tracing::warn;

use sctk::reexports::client::protocol::wl_keyboard::WlKeyboard;
use sctk::reexports::client::protocol::wl_keyboard::{
Expand Down
Loading

0 comments on commit 9443476

Please sign in to comment.