From 9485b45e705e3d853f4df2e402e15a3981d78225 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcel=20M=C3=A4rtens?= Date: Sun, 21 Jun 2020 23:47:49 +0200 Subject: [PATCH] switch to `tracing` stlye and enhance logs with usefull information - Updated CHANGELOG - reduce dependencies - found out that we have alot of duplicate coding... alot... --- CHANGELOG.md | 1 + Cargo.lock | 12 ----- chat-cli/Cargo.toml | 2 +- client/Cargo.toml | 2 +- client/src/lib.rs | 8 ++-- common/Cargo.toml | 2 +- common/src/assets/mod.rs | 14 +++--- common/src/assets/watch.rs | 6 +-- common/src/sync/packet.rs | 8 ++-- common/src/sync/sync_ext.rs | 4 +- common/src/util/dir.rs | 14 ++++-- server-cli/Cargo.toml | 2 +- server-cli/src/main.rs | 2 +- server/Cargo.toml | 2 +- server/src/auth_provider.rs | 6 +-- server/src/cmd.rs | 4 +- server/src/events/entity_manipulation.rs | 14 +++--- server/src/events/interaction.rs | 26 ++++------ server/src/events/inventory_manip.rs | 7 ++- server/src/events/player.rs | 12 +++-- server/src/lib.rs | 19 ++++---- server/src/metrics.rs | 6 +-- server/src/persistence/character.rs | 41 ++++++++-------- server/src/persistence/mod.rs | 12 ++--- server/src/persistence/models.rs | 8 ++-- server/src/settings.rs | 4 +- server/src/state_ext.rs | 12 ++--- server/src/sys/message.rs | 10 ++-- server/src/sys/subscription.rs | 5 +- voxygen/Cargo.toml | 4 +- voxygen/src/anim/src/dyn_lib.rs | 12 ++--- voxygen/src/anim/src/lib.rs | 8 ++-- voxygen/src/audio/soundcache.rs | 2 +- voxygen/src/ecs/sys/interpolation.rs | 2 +- voxygen/src/hud/item_imgs.rs | 14 ++---- voxygen/src/logging.rs | 13 ++--- voxygen/src/main.rs | 39 +++++++-------- voxygen/src/menu/char_selection/mod.rs | 4 +- voxygen/src/menu/main/mod.rs | 8 ++-- voxygen/src/meta.rs | 14 +++--- voxygen/src/profile.rs | 19 ++++---- voxygen/src/render/renderer.rs | 5 +- voxygen/src/scene/figure/load.rs | 29 ++++++------ voxygen/src/scene/simple.rs | 4 +- voxygen/src/settings.rs | 16 +++---- voxygen/src/ui/graphic/mod.rs | 11 +++-- voxygen/src/window.rs | 21 ++++----- world/Cargo.toml | 2 +- world/examples/water.rs | 8 ++-- world/src/civ/mod.rs | 2 +- world/src/column/mod.rs | 8 ++-- world/src/sim/erosion.rs | 2 +- world/src/sim/mod.rs | 60 +++++++++++------------- 53 files changed, 275 insertions(+), 297 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d2634c4bb..589b305a28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Energy regen resets on last ability use instead of on wield - Fixed unable to use ability; Secondary and ability3 (fire rod) will now automatically wield - Gliding is now a toggle that can be triggered from the ground +- Replaced `log` with `tracing` in all crates ### Removed diff --git a/Cargo.lock b/Cargo.lock index c5e2dd44b2..7c3998c28b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4187,7 +4187,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a41f40ed0e162c911ac6fcb53ecdc8134c46905fdbbae8c50add462a538b495f" dependencies = [ "cfg-if", - "tracing-attributes", "tracing-core", ] @@ -4202,17 +4201,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "tracing-attributes" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99bbad0de3fd923c9c3232ead88510b783e5a4d16a6154adffa3d53308de984c" -dependencies = [ - "proc-macro2 1.0.18", - "quote 1.0.7", - "syn 1.0.31", -] - [[package]] name = "tracing-core" version = "0.1.10" diff --git a/chat-cli/Cargo.toml b/chat-cli/Cargo.toml index 253fee4334..20acca2c87 100644 --- a/chat-cli/Cargo.toml +++ b/chat-cli/Cargo.toml @@ -8,5 +8,5 @@ edition = "2018" client = { package = "veloren-client", path = "../client" } common = { package = "veloren-common", path = "../common" } -tracing = { version = "0.1", default-features = false , features = ["attributes"] } +tracing = { version = "0.1", default-features = false } tracing-subscriber = { version = "0.2.3", default-features = false, features = ["fmt", "chrono", "ansi", "smallvec"] } diff --git a/client/Cargo.toml b/client/Cargo.toml index 8960b700ea..73fe3dc06e 100644 --- a/client/Cargo.toml +++ b/client/Cargo.toml @@ -11,7 +11,7 @@ byteorder = "1.3.2" uvth = "3.1.1" image = { version = "0.22.3", default-features = false, features = ["png"] } num_cpus = "1.10.1" -tracing = { version = "0.1", default-features = false , features = ["attributes"] } +tracing = { version = "0.1", default-features = false } specs = "0.15.1" vek = { version = "0.11.0", features = ["serde"] } hashbrown = { version = "0.6", features = ["rayon", "serde", "nightly"] } diff --git a/client/src/lib.rs b/client/src/lib.rs index 6f21487b4e..bfd16b278c 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -522,7 +522,7 @@ impl Client { // 1) Handle input from frontend. // Pass character actions from frontend input to the player's entity. if let ClientState::Character = self.client_state { - if let Err(err) = self + if let Err(e) = self .state .ecs() .write_storage::() @@ -537,9 +537,11 @@ impl Client { .inputs = inputs.clone(); }) { + let entry = self.entity; error!( - "Couldn't access controller component on client entity: {:?}", - err + ?e, + ?entry, + "Couldn't access controller component on client entity" ); } self.postbox diff --git a/common/Cargo.toml b/common/Cargo.toml index 0962224906..7773463a68 100644 --- a/common/Cargo.toml +++ b/common/Cargo.toml @@ -20,7 +20,7 @@ serde_derive = "1.0" serde_json = "1.0.41" ron = { version = "0.6", default-features = false } bincode = "1.2.0" -tracing = { version = "0.1", default-features = false , features = ["attributes"] } +tracing = { version = "0.1", default-features = false } rand = "0.7" rayon = "^1.3.0" lazy_static = "1.4.0" diff --git a/common/src/assets/mod.rs b/common/src/assets/mod.rs index 86c427970f..e982ee366e 100644 --- a/common/src/assets/mod.rs +++ b/common/src/assets/mod.rs @@ -14,7 +14,7 @@ use std::{ path::PathBuf, sync::{Arc, RwLock}, }; -use tracing::{debug, error, trace}; +use tracing::{trace, error}; /// The error returned by asset loading functions #[derive(Debug, Clone)] @@ -120,8 +120,8 @@ pub fn load_glob(specifier: &str) -> Result>> load(&specifier.replace("*", &name)) .map_err(|e| { error!( - "Failed to load \"{}\" as part of glob \"{}\" with error: {:?}", - name, specifier, e + ?e, + "Failed to load \"{}\" as part of glob \"{}\"", name, specifier ) }) .ok() @@ -204,8 +204,8 @@ pub fn load_watched( indicator.add( path_with_extension.ok_or_else(|| Error::NotFound(path.to_string_lossy().into_owned()))?, move || { - if let Err(err) = reload::(&owned_specifier) { - error!("Error reloading {}: {:#?}", &owned_specifier, err); + if let Err(e) = reload::(&owned_specifier) { + error!(?e, ?owned_specifier, "Error reloading owned_specifier"); } }, ); @@ -351,7 +351,7 @@ pub fn load_file(specifier: &str, endings: &[&str]) -> Result, E let mut path = path.clone(); path.set_extension(ending); - trace!("Trying to access \"{:?}\"", path); + trace!(?path, "Trying to access"); if let Ok(file) = File::open(path) { return Ok(BufReader::new(file)); } @@ -367,7 +367,7 @@ pub fn load_file_glob(specifier: &str, endings: &[&str]) -> Result { - if let Err(err) = self.watcher.watch(path.clone(), RecursiveMode::Recursive) { - warn!("Could not start watching {:#?} due to: {}", &path, err); + if let Err(e) = self.watcher.watch(path.clone(), RecursiveMode::Recursive) { + warn!(?e, ?path, "Could not start watching file"); return; } self.watching.insert(path, (handler, vec![signal])); @@ -121,7 +121,7 @@ impl Watcher { recv(self.event_rx) -> res => match res { Ok(Ok(event)) => self.handle_event(event), // Notify Error - Ok(Err(err)) => error!("Notify error: {}", err), + Ok(Err(e)) => error!(?e, "Notify error"), // Disconnected Err(_) => (), }, diff --git a/common/src/sync/packet.rs b/common/src/sync/packet.rs index b0e764792d..ed9d93f4d2 100644 --- a/common/src/sync/packet.rs +++ b/common/src/sync/packet.rs @@ -21,8 +21,8 @@ pub trait CompPacket: Clone + Debug + Send + 'static { /// Useful for implementing CompPacket trait pub fn handle_insert(comp: C, entity: Entity, world: &World) { - if let Err(err) = world.write_storage::().insert(entity, comp) { - error!("Error inserting : {:?}", err); + if let Err(e) = world.write_storage::().insert(entity, comp) { + error!(?e, "Error inserting"); } } /// Useful for implementing CompPacket trait @@ -31,8 +31,8 @@ pub fn handle_modify(comp: C, entity: Entity, world: &Worl *c = comp } else { error!( - "Error modifying synced component: {:?}, it doesn't seem to exist", - comp + ?comp, + "Error modifying synced component, it doesn't seem to exist" ); } } diff --git a/common/src/sync/sync_ext.rs b/common/src/sync/sync_ext.rs index 2dd6eb5686..17ac09fff9 100644 --- a/common/src/sync/sync_ext.rs +++ b/common/src/sync/sync_ext.rs @@ -90,8 +90,8 @@ impl WorldSyncExt for specs::World { // Clear from uid allocator let maybe_entity = self.write_resource::().remove_entity(uid); if let Some(entity) = maybe_entity { - if let Err(err) = self.delete_entity(entity) { - error!("Failed to delete entity: {:?}", err); + if let Err(e) = self.delete_entity(entity) { + error!(?e, "Failed to delete entity"); } } } diff --git a/common/src/util/dir.rs b/common/src/util/dir.rs index 5ce7636b12..41bfe0ffbd 100644 --- a/common/src/util/dir.rs +++ b/common/src/util/dir.rs @@ -19,10 +19,16 @@ impl From for Dir { fn from(dir: SerdeDir) -> Self { let dir = dir.0; if dir.map(f32::is_nan).reduce_or() { - warn!("Deserialized dir containing NaNs, replacing with default"); + warn!( + ?dir, + "Deserialized dir containing NaNs, replacing with default" + ); Default::default() } else if !dir.is_normalized() { - warn!("Deserialized unnormalized dir, replacing with default"); + warn!( + ?dir, + "Deserialized unnormalized dir, replacing with default" + ); Default::default() } else { Self(dir) @@ -109,7 +115,7 @@ fn slerp_normalized(from: vek::Vec3, to: vek::Vec3, factor: f32) -> ve }; if unnormalized { - panic!("Called slerp_normalized with unnormalized from: {:?}", from); + panic!("Called slerp_normalized with unnormalized `from`: {}", from); } } @@ -122,7 +128,7 @@ fn slerp_normalized(from: vek::Vec3, to: vek::Vec3, factor: f32) -> ve }; if unnormalized { - panic!("Called slerp_normalized with unnormalized to: {:?}", to); + panic!("Called slerp_normalized with unnormalized `to`: {}", to); } } diff --git a/server-cli/Cargo.toml b/server-cli/Cargo.toml index 708bc2558d..2f46bb8e13 100644 --- a/server-cli/Cargo.toml +++ b/server-cli/Cargo.toml @@ -12,5 +12,5 @@ default = ["worldgen"] server = { package = "veloren-server", path = "../server", default-features = false } common = { package = "veloren-common", path = "../common" } -tracing = { version = "0.1", default-features = false , features = ["attributes"] } +tracing = { version = "0.1", default-features = false } tracing-subscriber = { version = "0.2.3", default-features = false, features = ["fmt", "chrono", "ansi", "smallvec"] } diff --git a/server-cli/src/main.rs b/server-cli/src/main.rs index d10437f5fa..d0fdd7ae61 100644 --- a/server-cli/src/main.rs +++ b/server-cli/src/main.rs @@ -30,7 +30,7 @@ fn main() { let mut server = Server::new(settings).expect("Failed to create server instance!"); info!("Server is ready to accept connections."); - info!("Metrics port: {}", metrics_port); + info!(?metrics_port, "starting metrics at port"); loop { let events = server diff --git a/server/Cargo.toml b/server/Cargo.toml index 94053ed6d0..5696b593a1 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -14,7 +14,7 @@ world = { package = "veloren-world", path = "../world" } specs-idvs = { git = "https://gitlab.com/veloren/specs-idvs.git" } -tracing = { version = "0.1", default-features = false , features = ["attributes"] } +tracing = { version = "0.1", default-features = false } specs = { version = "0.15.1", features = ["shred-derive"] } vek = "0.11.0" uvth = "3.1.1" diff --git a/server/src/auth_provider.rs b/server/src/auth_provider.rs index 14156bd398..d08f8e5b63 100644 --- a/server/src/auth_provider.rs +++ b/server/src/auth_provider.rs @@ -35,7 +35,7 @@ impl AuthProvider { pub fn logout(&mut self, uuid: Uuid) { if self.accounts.remove(&uuid).is_none() { - error!("Attempted to logout user that is not logged in."); + error!(?uuid, "Attempted to logout user that is not logged in."); }; } @@ -45,7 +45,7 @@ impl AuthProvider { match &self.auth_server { // Token from auth server expected Some(srv) => { - info!("Validating '{}' token.", &username_or_token); + info!(?username_or_token, "Validating token"); // Parse token let token = AuthToken::from_str(&username_or_token) .map_err(|e| RegisterError::AuthError(e.to_string()))?; @@ -66,7 +66,7 @@ impl AuthProvider { let username = username_or_token; let uuid = derive_uuid(&username); if !self.accounts.contains_key(&uuid) { - info!("New User '{}'", username); + info!(?username, "New User"); self.accounts.insert(uuid, username.clone()); Ok((username, uuid)) } else { diff --git a/server/src/cmd.rs b/server/src/cmd.rs index 7ce557f6a3..bbceca466e 100644 --- a/server/src/cmd.rs +++ b/server/src/cmd.rs @@ -1265,8 +1265,8 @@ fn handle_remove_lights( let size = to_delete.len(); for entity in to_delete { - if let Err(err) = server.state.delete_entity_recorded(entity) { - error!("Failed to delete light: {:?}", err); + if let Err(e) = server.state.delete_entity_recorded(entity) { + error!(?e, "Failed to delete light: {:?}", e); } } diff --git a/server/src/events/entity_manipulation.rs b/server/src/events/entity_manipulation.rs index c049a65b07..8de46e9df8 100644 --- a/server/src/events/entity_manipulation.rs +++ b/server/src/events/entity_manipulation.rs @@ -80,13 +80,13 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, cause: HealthSourc .write_storage() .insert(entity, comp::Vel(Vec3::zero())) .err() - .map(|err| error!("Failed to set zero vel on dead client: {:?}", err)); + .map(|e| error!(?e, ?entity, "Failed to set zero vel on dead client")); state .ecs() .write_storage() .insert(entity, comp::ForceUpdate) .err() - .map(|err| error!("Failed to insert ForceUpdate on dead client: {:?}", err)); + .map(|e| error!(?e, ?entity, "Failed to insert ForceUpdate on dead client")); state .ecs() .write_storage::() @@ -306,14 +306,14 @@ pub fn handle_destroy(server: &mut Server, entity: EcsEntity, cause: HealthSourc } else { let _ = state .delete_entity_recorded(entity) - .map_err(|err| error!("Failed to delete destroyed entity: {:?}", err)); + .map_err(|e| error!(?e, ?entity, "Failed to delete destroyed entity")); } // TODO: Add Delete(time_left: Duration) component /* // If not a player delete the entity if let Err(err) = state.delete_entity_recorded(entity) { - error!("Failed to delete destroyed entity: {:?}", err); + error!(?e, "Failed to delete destroyed entity"); } */ } @@ -361,10 +361,10 @@ pub fn handle_respawn(server: &Server, entity: EcsEntity) { .write_storage() .insert(entity, comp::ForceUpdate) .err() - .map(|err| { + .map(|e| { error!( - "Error inserting ForceUpdate component when respawning client: {:?}", - err + ?e, + "Error inserting ForceUpdate component when respawning client" ) }); } diff --git a/server/src/events/interaction.rs b/server/src/events/interaction.rs index 28d13870b8..9189803e55 100644 --- a/server/src/events/interaction.rs +++ b/server/src/events/interaction.rs @@ -121,12 +121,10 @@ pub fn handle_possess(server: &Server, possessor_uid: Uid, possesse_uid: Uid) { if clients.get_mut(possesse).is_none() { if let Some(mut client) = clients.remove(possessor) { client.notify(ServerMsg::SetPlayerEntity(possesse_uid.into())); - clients.insert(possesse, client).err().map(|e| { - error!( - "Error inserting client component during possession: {:?}", - e - ) - }); + clients + .insert(possesse, client) + .err() + .map(|e| error!(?e, "Error inserting client component during possession")); // Put possess item into loadout let mut loadouts = ecs.write_storage::(); let loadout = loadouts @@ -155,10 +153,7 @@ pub fn handle_possess(server: &Server, possessor_uid: Uid, possesse_uid: Uid) { let mut players = ecs.write_storage::(); if let Some(player) = players.remove(possessor) { players.insert(possesse, player).err().map(|e| { - error!( - "Error inserting player component during possession: {:?}", - e - ) + error!(?e, "Error inserting player component during possession") }); } } @@ -168,8 +163,8 @@ pub fn handle_possess(server: &Server, possessor_uid: Uid, possesse_uid: Uid) { if let Some(s) = subscriptions.remove(possessor) { subscriptions.insert(possesse, s).err().map(|e| { error!( - "Error inserting subscription component during possession: {:?}", - e + ?e, + "Error inserting subscription component during possession" ) }); } @@ -185,7 +180,7 @@ pub fn handle_possess(server: &Server, possessor_uid: Uid, possesse_uid: Uid) { let mut admins = ecs.write_storage::(); if let Some(admin) = admins.remove(possessor) { admins.insert(possesse, admin).err().map(|e| { - error!("Error inserting admin component during possession: {:?}", e) + error!(?e, "Error inserting admin component during possession") }); } } @@ -194,10 +189,7 @@ pub fn handle_possess(server: &Server, possessor_uid: Uid, possesse_uid: Uid) { let mut waypoints = ecs.write_storage::(); if let Some(waypoint) = waypoints.remove(possessor) { waypoints.insert(possesse, waypoint).err().map(|e| { - error!( - "Error inserting waypoint component during possession {:?}", - e - ) + error!(?e, "Error inserting waypoint component during possession",) }); } } diff --git a/server/src/events/inventory_manip.rs b/server/src/events/inventory_manip.rs index 4c4c7b109f..a07d50adb2 100644 --- a/server/src/events/inventory_manip.rs +++ b/server/src/events/inventory_manip.rs @@ -108,7 +108,10 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv let inventory = if let Some(inventory) = inventories.get_mut(entity) { inventory } else { - error!("Can't manipulate inventory, entity doesn't have one"); + error!( + ?entity, + "Can't manipulate inventory, entity doesn't have one" + ); return; }; @@ -220,7 +223,7 @@ pub fn handle_inventory(server: &mut Server, entity: EcsEntity, manip: comp::Inv slot::unequip(slot, inventory, loadout); Some(comp::InventoryUpdateEvent::Used) } else { - error!("Entity doesn't have a loadout, can't unequip..."); + error!(?entity, "Entity doesn't have a loadout, can't unequip..."); None } }, diff --git a/server/src/events/player.rs b/server/src/events/player.rs index 9039d990cc..ce5f476e00 100644 --- a/server/src/events/player.rs +++ b/server/src/events/player.rs @@ -36,8 +36,12 @@ pub fn handle_exit_ingame(server: &mut Server, entity: EcsEntity) { entity_builder.with(uid).build(); } // Delete old entity - if let Err(err) = state.delete_entity_recorded(entity) { - error!("Failed to delete entity when removing character: {:?}", err); + if let Err(e) = state.delete_entity_recorded(entity) { + error!( + ?e, + ?entity, + "Failed to delete entity when removing character" + ); } } @@ -87,8 +91,8 @@ pub fn handle_client_disconnect(server: &mut Server, entity: EcsEntity) -> Event } // Delete client entity - if let Err(err) = state.delete_entity_recorded(entity) { - error!("Failed to delete disconnected client: {:?}", err); + if let Err(e) = state.delete_entity_recorded(entity) { + error!(?e, ?entity, "Failed to delete disconnected client"); } Event::ClientDisconnected { entity } diff --git a/server/src/lib.rs b/server/src/lib.rs index 26d961a802..db19408fc0 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -253,19 +253,16 @@ impl Server { // Run pending DB migrations (if any) debug!("Running DB migrations..."); - if let Some(error) = - persistence::run_migrations(&this.server_settings.persistence_db_dir).err() + if let Some(e) = persistence::run_migrations(&this.server_settings.persistence_db_dir).err() { - info!("Migration error: {}", format!("{:#?}", error)); + info!(?e, "Migration error"); } - debug!("created veloren server with: {:?}", &settings); + debug!(?settings, "created veloren server with"); - info!( - "Server version: {}[{}]", - *common::util::GIT_HASH, - *common::util::GIT_DATE - ); + let git_hash = *common::util::GIT_HASH; + let git_date = *common::util::GIT_DATE; + info!(?git_hash, ?git_date, "Server version",); Ok(this) } @@ -378,8 +375,8 @@ impl Server { .collect::>() }; for entity in to_delete { - if let Err(err) = self.state.delete_entity_recorded(entity) { - error!("Failed to delete agent outside the terrain: {:?}", err); + if let Err(e) = self.state.delete_entity_recorded(entity) { + error!(?e, "Failed to delete agent outside the terrain"); } } diff --git a/server/src/metrics.rs b/server/src/metrics.rs index 5169bbc5ac..a5e1c915b3 100644 --- a/server/src/metrics.rs +++ b/server/src/metrics.rs @@ -142,7 +142,7 @@ impl ServerMetrics { Ok(Some(rq)) => rq, Ok(None) => continue, Err(e) => { - println!("error: {}", e); + error!(?e, "metrics http server error"); break; }, }; @@ -157,8 +157,8 @@ impl ServerMetrics { ); if let Err(e) = request.respond(response) { error!( - "The metrics HTTP server had encountered and error with answering, {}", - e + ?e, + "The metrics HTTP server had encountered and error with answering", ); } } diff --git a/server/src/persistence/character.rs b/server/src/persistence/character.rs index 248f38f08d..58a08594ff 100644 --- a/server/src/persistence/character.rs +++ b/server/src/persistence/character.rs @@ -77,13 +77,15 @@ pub fn load_character_data( let row = NewLoadout::from((character_data.id, &default_loadout)); - if let Err(error) = diesel::insert_into(schema::loadout::table) + if let Err(e) = diesel::insert_into(schema::loadout::table) .values(&row) .execute(&connection) { + let char_id = character_data.id; warn!( - "Failed to create an loadout record for character {}: {}", - &character_data.id, error + ?e, + ?char_id, + "Failed to create an loadout record for character", ) } @@ -314,8 +316,8 @@ impl CharacterUpdater { }) .collect(); - if let Err(err) = self.update_tx.as_ref().unwrap().send(updates) { - error!("Could not send stats updates: {:?}", err); + if let Err(e) = self.update_tx.as_ref().unwrap().send(updates) { + error!(?e, "Could not send stats updates"); } } @@ -333,7 +335,7 @@ impl CharacterUpdater { fn batch_update(updates: impl Iterator, db_dir: &str) { let connection = establish_connection(db_dir); - if let Err(err) = connection.transaction::<_, diesel::result::Error, _>(|| { + if let Err(e) = connection.transaction::<_, diesel::result::Error, _>(|| { updates.for_each( |(character_id, (stats_update, inventory_update, loadout_update))| { update( @@ -348,7 +350,7 @@ fn batch_update(updates: impl Iterator, db_di Ok(()) }) { - error!("Error during stats batch update transaction: {:?}", err); + error!(?e, "Error during stats batch update transaction"); } } @@ -359,47 +361,42 @@ fn update( loadout: &LoadoutUpdate, connection: &SqliteConnection, ) { - if let Err(error) = + if let Err(e) = diesel::update(schema::stats::table.filter(schema::stats::character_id.eq(character_id))) .set(stats) .execute(connection) { - warn!( - "Failed to update stats for character: {:?}: {:?}", - character_id, error - ) + warn!(?e, ?character_id, "Failed to update stats for character",) } - if let Err(error) = diesel::update( + if let Err(e) = diesel::update( schema::inventory::table.filter(schema::inventory::character_id.eq(character_id)), ) .set(inventory) .execute(connection) { warn!( - "Failed to update inventory for character: {:?}: {:?}", - character_id, error + ?e, + ?character_id, + "Failed to update inventory for character", ) } - if let Err(error) = diesel::update( + if let Err(e) = diesel::update( schema::loadout::table.filter(schema::loadout::character_id.eq(character_id)), ) .set(loadout) .execute(connection) { - warn!( - "Failed to update loadout for character: {:?}: {:?}", - character_id, error - ) + warn!(?e, ?character_id, "Failed to update loadout for character",) } } impl Drop for CharacterUpdater { fn drop(&mut self) { drop(self.update_tx.take()); - if let Err(err) = self.handle.take().unwrap().join() { - error!("Error from joining character update thread: {:?}", err); + if let Err(e) = self.handle.take().unwrap().join() { + error!(?e, "Error from joining character update thread"); } } } diff --git a/server/src/persistence/mod.rs b/server/src/persistence/mod.rs index fc3389053f..25363b00e3 100644 --- a/server/src/persistence/mod.rs +++ b/server/src/persistence/mod.rs @@ -31,16 +31,16 @@ fn establish_connection(db_dir: &str) -> SqliteConnection { // Use Write-Ahead-Logging for improved concurrency: https://sqlite.org/wal.html // Set a busy timeout (in ms): https://sqlite.org/c3ref/busy_timeout.html - if let Err(error) = connection.batch_execute( + if let Err(e) = connection.batch_execute( " PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 250; ", ) { warn!( + ?e, "Failed adding PRAGMA statements while establishing sqlite connection, this will \ - result in a higher likelihood of locking errors: {}", - error + result in a higher likelihood of locking errors" ); } @@ -49,8 +49,8 @@ fn establish_connection(db_dir: &str) -> SqliteConnection { #[allow(clippy::single_match)] // TODO: Pending review in #587 fn apply_saves_dir_override(db_dir: &str) -> String { - if let Some(val) = env::var_os("VELOREN_SAVES_DIR") { - let path = PathBuf::from(val); + if let Some(saves_dir) = env::var_os("VELOREN_SAVES_DIR") { + let path = PathBuf::from(saves_dir.clone()); if path.exists() || path.parent().map(|x| x.exists()).unwrap_or(false) { // Only allow paths with valid unicode characters match path.to_str() { @@ -58,7 +58,7 @@ fn apply_saves_dir_override(db_dir: &str) -> String { None => {}, } } - warn!("VELOREN_SAVES_DIR points to an invalid path."); + warn!(?saves_dir, "VELOREN_SAVES_DIR points to an invalid path."); } db_dir.to_string() } diff --git a/server/src/persistence/models.rs b/server/src/persistence/models.rs index a717376e97..9e4c910425 100644 --- a/server/src/persistence/models.rs +++ b/server/src/persistence/models.rs @@ -173,8 +173,8 @@ where match serde_json::from_str(&t) { Ok(data) => Ok(Self(data)), - Err(error) => { - warn!("Failed to deserialise inventory data: {}", error); + Err(e) => { + warn!(?e, "Failed to deserialise inventory data"); Ok(Self(comp::Inventory::default())) }, } @@ -259,8 +259,8 @@ where match serde_json::from_str(&t) { Ok(data) => Ok(Self(data)), - Err(error) => { - warn!("Failed to deserialise loadout data: {}", error); + Err(e) => { + warn!(?e, "Failed to deserialise loadout data"); // We don't have a weapon reference here, so we default to sword let loadout = LoadoutBuilder::new() diff --git a/server/src/settings.rs b/server/src/settings.rs index d8d17b0117..9cb9c60de2 100644 --- a/server/src/settings.rs +++ b/server/src/settings.rs @@ -72,7 +72,7 @@ impl ServerSettings { match ron::de::from_reader(file) { Ok(x) => x, Err(e) => { - warn!("Failed to parse setting file! Fallback to default. {}", e); + warn!(?e, "Failed to parse setting file! Fallback to default"); Self::default() }, } @@ -80,7 +80,7 @@ impl ServerSettings { let default_settings = Self::default(); match default_settings.save_to_file() { - Err(e) => error!("Failed to create default setting file! {}", e), + Err(e) => error!(?e, "Failed to create default setting file!"), _ => {}, } default_settings diff --git a/server/src/state_ext.rs b/server/src/state_ext.rs index 551be9886b..88abc1afb4 100644 --- a/server/src/state_ext.rs +++ b/server/src/state_ext.rs @@ -172,13 +172,11 @@ impl StateExt for State { self.write_component(entity, inventory); self.write_component(entity, loadout); }, - Err(error) => { + Err(e) => { warn!( - "{}", - format!( - "Failed to load character data for character_id {}: {}", - character_id, error - ) + ?e, + ?character_id, + "Failed to load character data for character_id" ); if let Some(client) = self.ecs().write_storage::().get_mut(entity) { @@ -295,6 +293,8 @@ impl StateExt for State { // and then deleted before the region manager had a chance to assign it a // region warn!( + ?uid, + ?pos, "Failed to find region containing entity during entity deletion, assuming \ it wasn't sent to any clients and so deletion doesn't need to be \ recorded for sync purposes" diff --git a/server/src/sys/message.rs b/server/src/sys/message.rs index 91ee00541d..84e8fc099c 100644 --- a/server/src/sys/message.rs +++ b/server/src/sys/message.rs @@ -275,11 +275,11 @@ impl<'a> System<'a> for Sys { | ClientState::Spectator | ClientState::Character => match validate_chat_msg(&message) { Ok(()) => new_chat_msgs.push((Some(entity), ServerMsg::chat(message))), - Err(ChatMsgValidationError::TooLong) => warn!( - "Recieved a chat message that's too long (max:{} len:{})", - MAX_BYTES_CHAT_MSG, - message.len() - ), + Err(ChatMsgValidationError::TooLong) => { + let max = MAX_BYTES_CHAT_MSG; + let len = message.len(); + warn!(?len, ?max, "Recieved a chat message that's too long") + }, }, ClientState::Pending => {}, }, diff --git a/server/src/sys/subscription.rs b/server/src/sys/subscription.rs index 39413a8450..7fd52d8613 100644 --- a/server/src/sys/subscription.rs +++ b/server/src/sys/subscription.rs @@ -259,14 +259,15 @@ pub fn initialize_region_subscription(world: &World, entity: specs::Entity) { } } - if let Err(err) = world.write_storage().insert(entity, RegionSubscription { + if let Err(e) = world.write_storage().insert(entity, RegionSubscription { fuzzy_chunk, regions, }) { - error!("Failed to insert region subscription component: {:?}", err); + error!(?e, "Failed to insert region subscription component"); } } else { debug!( + ?entity, "Failed to initialize region subcription. Couldn't retrieve all the neccesary \ components on the provided entity" ); diff --git a/voxygen/Cargo.toml b/voxygen/Cargo.toml index 2366ff3043..4f1cea843a 100644 --- a/voxygen/Cargo.toml +++ b/voxygen/Cargo.toml @@ -72,8 +72,8 @@ authc = { git = "https://gitlab.com/veloren/auth.git", rev = "223a4097f7ebc8d451 const-tweaker = { version = "0.2.5", optional = true } # Logging -tracing = { version = "0.1", default-features = false , features = ["attributes"] } -tracing-subscriber = { version = "0.2.3", default-features = false, features = ["env-filter", "fmt", "chrono", "ansi", "smallvec", "registry", "tracing-log"] } +tracing = { version = "0.1", default-features = false } +tracing-subscriber = { version = "0.2.3", default-features = false, features = ["env-filter", "fmt", "chrono", "ansi", "smallvec" , "tracing-log"] } tracing-log = "0.1.1" tracing-appender = "0.1" diff --git a/voxygen/src/anim/src/dyn_lib.rs b/voxygen/src/anim/src/dyn_lib.rs index a0f4505bea..b6b5d36c8a 100644 --- a/voxygen/src/anim/src/dyn_lib.rs +++ b/voxygen/src/anim/src/dyn_lib.rs @@ -62,14 +62,10 @@ pub fn init() { modified_paths.insert(path); } - let mut info = "Hot reloading animations because these files were modified:".to_owned(); - for path in std::mem::take(&mut modified_paths) { - info.push('\n'); - info.push('\"'); - info.push_str(&path); - info.push('\"'); - } - warn!("{}", info); + warn!( + ?modified_paths, + "Hot reloading animations because these files were modified" + ); // Reload reload(); diff --git a/voxygen/src/anim/src/lib.rs b/voxygen/src/anim/src/lib.rs index 766775c36d..0afdbbbae5 100644 --- a/voxygen/src/anim/src/lib.rs +++ b/voxygen/src/anim/src/lib.rs @@ -86,14 +86,14 @@ pub trait Skeleton: Send + Sync + 'static { let lib = &lock.as_ref().unwrap().lib; let compute_fn: libloading::Symbol ([FigureBoneData; 16], Vec3)> = - unsafe { lib.get(Self::COMPUTE_FN) }.unwrap_or_else(|err| { + unsafe { lib.get(Self::COMPUTE_FN) }.unwrap_or_else(|e| { panic!( "Trying to use: {} but had error: {:?}", CStr::from_bytes_with_nul(Self::COMPUTE_FN) .map(CStr::to_str) .unwrap() .unwrap(), - err + e ) }); @@ -154,14 +154,14 @@ pub trait Animation { //println!("{}", start.elapsed().as_nanos()); f } - .unwrap_or_else(|err| { + .unwrap_or_else(|e| { panic!( "Trying to use: {} but had error: {:?}", CStr::from_bytes_with_nul(Self::UPDATE_FN) .map(CStr::to_str) .unwrap() .unwrap(), - err + e ) }); diff --git a/voxygen/src/audio/soundcache.rs b/voxygen/src/audio/soundcache.rs index 8add632140..61488e3e56 100644 --- a/voxygen/src/audio/soundcache.rs +++ b/voxygen/src/audio/soundcache.rs @@ -53,7 +53,7 @@ impl SoundCache { .entry(name.to_string()) .or_insert_with(|| { Sound::load(name).unwrap_or_else(|_| { - warn!("SoundCache: Failed to load sound: {}", name); + warn!(?name, "SoundCache: Failed to load sound"); Sound::empty() }) diff --git a/voxygen/src/ecs/sys/interpolation.rs b/voxygen/src/ecs/sys/interpolation.rs index 9d7307e758..626d86d65f 100644 --- a/voxygen/src/ecs/sys/interpolation.rs +++ b/voxygen/src/ecs/sys/interpolation.rs @@ -46,7 +46,7 @@ impl<'a> System<'a> for Sys { interpolated .insert(entity, Interpolated { pos, ori }) .err() - .map(|err| warn!("Error inserting Interpolated component: {}", err)); + .map(|e| warn!(?e, "Error inserting Interpolated component")); } // Remove Interpolated component from entities which don't have a position or an // orientation or a velocity diff --git a/voxygen/src/hud/item_imgs.rs b/voxygen/src/hud/item_imgs.rs index 40c9d98c36..e6383e0c81 100644 --- a/voxygen/src/hud/item_imgs.rs +++ b/voxygen/src/hud/item_imgs.rs @@ -141,8 +141,8 @@ impl ItemImgs { // There was no specification in the ron None => { warn!( - "{:?} has no specified image file (note: hot-reloading won't work here)", - item_kind + ?item_kind, + "missing specified image file (note: hot-reloading won't work here)", ); None }, @@ -161,10 +161,7 @@ fn graceful_load_vox(specifier: &str) -> Arc { match assets::load::(full_specifier.as_str()) { Ok(dot_vox) => dot_vox, Err(_) => { - error!( - "Could not load vox file for item images: {}", - full_specifier - ); + error!(?full_specifier, "Could not load vox file for item images",); assets::load_expect::("voxygen.voxel.not_found") }, } @@ -174,10 +171,7 @@ fn graceful_load_img(specifier: &str) -> Arc { match assets::load::(full_specifier.as_str()) { Ok(img) => img, Err(_) => { - error!( - "Could not load image file for item images: {}", - full_specifier - ); + error!(?full_specifier, "Could not load image file for item images"); assets::load_expect::("voxygen.element.not_found") }, } diff --git a/voxygen/src/logging.rs b/voxygen/src/logging.rs index f96dfdca7b..ab6b0e2949 100644 --- a/voxygen/src/logging.rs +++ b/voxygen/src/logging.rs @@ -2,7 +2,7 @@ use std::fs; use crate::settings::Settings; -use tracing::{error, info, instrument}; +use tracing::{error, info}; use tracing_subscriber::{filter::LevelFilter, prelude::*, registry, EnvFilter}; const VOXYGEN_LOG_ENV: &str = "VOXYGEN_LOG"; @@ -20,7 +20,6 @@ const VOXYGEN_LOG_ENV: &str = "VOXYGEN_LOG"; /// following in your environment. /// /// `VOXYGEN_LOG="veloren_voxygen=trace"` -#[instrument] pub fn init(settings: &Settings) -> Vec { // To hold the guards that we create, they will cause the logs to be // flushed when they're dropped. @@ -44,13 +43,14 @@ pub fn init(settings: &Settings) -> Vec { // Try to create the log file's parent folders. let log_folders_created = fs::create_dir_all(&settings.log.logs_path); + const LOG_FILENAME: &str = "voxygen.log"; match log_folders_created { // If the parent folders were created then attach both a terminal and a // file writer to the registry and init it. Ok(_) => { let file_appender = - tracing_appender::rolling::daily(&settings.log.logs_path, "voxygen.log"); + tracing_appender::rolling::daily(&settings.log.logs_path, LOG_FILENAME); let (non_blocking_file, _file_guard) = tracing_appender::non_blocking(file_appender); _guards.push(_file_guard); registry() @@ -58,13 +58,14 @@ pub fn init(settings: &Settings) -> Vec { .with(tracing_subscriber::fmt::layer().with_writer(non_blocking_file)) .with(filter) .init(); - info!("Setup terminal and file logging."); + let logdir = &settings.log.logs_path; + info!(?logdir, "Setup terminal and file logging."); }, // Otherwise just add a terminal writer and init it. Err(e) => { error!( - "Failed to create log file! {}. Falling back to terminal logging only.", - e + ?e, + "Failed to create log file!. Falling back to terminal logging only.", ); registry() .with(tracing_subscriber::fmt::layer().with_writer(non_blocking)) diff --git a/voxygen/src/main.rs b/voxygen/src/main.rs index eae9810bb4..b4f64dc017 100644 --- a/voxygen/src/main.rs +++ b/voxygen/src/main.rs @@ -16,9 +16,8 @@ use veloren_voxygen::{ use common::assets::{load, load_expect}; use std::{mem, panic}; -use tracing::{debug, error, instrument, warn}; +use tracing::{debug, error, warn}; -#[instrument] fn main() { #[cfg(feature = "tweak")] const_tweaker::run().expect("Could not run server"); @@ -65,11 +64,12 @@ fn main() { let localized_strings = load::(&i18n_asset_key( &global_state.settings.language.selected_language, )) - .unwrap_or_else(|error| { + .unwrap_or_else(|e| { + let preferred_language = &global_state.settings.language.selected_language; warn!( - "Impossible to load {} language: change to the default language (English) instead. \ - Source error: {:?}", - &global_state.settings.language.selected_language, error + ?e, + ?preferred_language, + "Impossible to load language: change to the default language (English) instead.", ); global_state.settings.language.selected_language = i18n::REFERENCE_LANG.to_owned(); load_expect::(&i18n_asset_key( @@ -161,9 +161,10 @@ fn main() { // Set up the initial play state. let mut states: Vec> = vec![Box::new(MainMenuState::new(&mut global_state))]; - states - .last() - .map(|current_state| debug!("Started game with state '{}'", current_state.name())); + states.last().map(|current_state| { + let current_state = current_state.name(); + debug!(?current_state, "Started game with state") + }); // What's going on here? // --------------------- @@ -185,7 +186,8 @@ fn main() { debug!("Shutting down all states..."); while states.last().is_some() { states.pop().map(|old_state| { - debug!("Popped state '{}'.", old_state.name()); + let old_state = old_state.name(); + debug!(?old_state, "Popped state"); global_state.on_play_state_changed(); }); } @@ -193,7 +195,8 @@ fn main() { PlayStateResult::Pop => { direction = Direction::Backwards; states.pop().map(|old_state| { - debug!("Popped state '{}'.", old_state.name()); + let old_state = old_state.name(); + debug!(?old_state, "Popped state"); global_state.on_play_state_changed(); }); }, @@ -203,15 +206,13 @@ fn main() { states.push(new_state); global_state.on_play_state_changed(); }, - PlayStateResult::Switch(mut new_state) => { + PlayStateResult::Switch(mut new_state_box) => { direction = Direction::Forwards; - states.last_mut().map(|old_state| { - debug!( - "Switching to state '{}' from state '{}'.", - new_state.name(), - old_state.name() - ); - mem::swap(old_state, &mut new_state); + states.last_mut().map(|old_state_box| { + let old_state = old_state_box.name(); + let new_state = new_state_box.name(); + debug!(?old_state, ?new_state, "Switching to states",); + mem::swap(old_state_box, &mut new_state_box); global_state.on_play_state_changed(); }); }, diff --git a/voxygen/src/menu/char_selection/mod.rs b/voxygen/src/menu/char_selection/mod.rs index 722fa3d431..51c2de60f5 100644 --- a/voxygen/src/menu/char_selection/mod.rs +++ b/voxygen/src/menu/char_selection/mod.rs @@ -156,14 +156,14 @@ impl PlayState for CharSelectionState { let localized_strings = assets::load_expect::(&i18n_asset_key( &global_state.settings.language.selected_language, )); - if let Err(err) = self.client.borrow_mut().tick( + if let Err(e) = self.client.borrow_mut().tick( comp::ControllerInputs::default(), clock.get_last_delta(), |_| {}, ) { global_state.info_message = Some(localized_strings.get("common.connection_lost").to_owned()); - error!("[char_selection] Failed to tick the scene: {:?}", err); + error!(?e, "[char_selection] Failed to tick the scene"); return PlayStateResult::Pop; } diff --git a/voxygen/src/menu/main/mod.rs b/voxygen/src/menu/main/mod.rs index 8ff712f37f..071b4a9a09 100644 --- a/voxygen/src/menu/main/mod.rs +++ b/voxygen/src/menu/main/mod.rs @@ -75,10 +75,10 @@ impl PlayState for MainMenuState { std::rc::Rc::new(std::cell::RefCell::new(client)), ))); }, - Some(InitMsg::Done(Err(err))) => { + Some(InitMsg::Done(Err(e))) => { client_init = None; global_state.info_message = Some({ - let err = match err { + let err = match e { InitError::BadAddress(_) | InitError::NoAddress => { localized_strings.get("main.login.server_not_found").into() }, @@ -262,8 +262,8 @@ fn attempt_login( if !net_settings.servers.contains(&server_address) { net_settings.servers.push(server_address.clone()); } - if let Err(err) = global_state.settings.save_to_file() { - warn!("Failed to save settings: {:?}", err); + if let Err(e) = global_state.settings.save_to_file() { + warn!(?e, "Failed to save settings"); } if comp::Player::alias_is_valid(&username) { diff --git a/voxygen/src/meta.rs b/voxygen/src/meta.rs index d3e568b790..30ef1a3c7b 100644 --- a/voxygen/src/meta.rs +++ b/voxygen/src/meta.rs @@ -47,13 +47,13 @@ impl Meta { } }, Err(e) => { - warn!("Failed to parse meta file! Fallback to default. {}", e); + warn!(?e, ?file, "Failed to parse meta file! Fallback to default"); // Rename the corrupted settings file let mut new_path = path.to_owned(); new_path.pop(); new_path.push("meta.invalid.ron"); - if let Err(err) = std::fs::rename(path, new_path) { - warn!("Failed to rename meta file. {}", err); + if let Err(e) = std::fs::rename(path.clone(), new_path.clone()) { + warn!(?e, ?path, ?new_path, "Failed to rename meta file"); } }, } @@ -68,7 +68,7 @@ impl Meta { pub fn save_to_file_warn(&self) { if let Err(err) = self.save_to_file() { - warn!("Failed to save settings: {:?}", err); + warn!(?e, "Failed to save settings"); } } @@ -85,12 +85,12 @@ impl Meta { } pub fn get_meta_path() -> PathBuf { - if let Some(val) = std::env::var_os("VOXYGEN_CONFIG") { - let meta = PathBuf::from(val).join("meta.ron"); + if let Some(path) = std::env::var_os("VOXYGEN_CONFIG") { + let meta = PathBuf::from(path).join("meta.ron"); if meta.exists() || meta.parent().map(|x| x.exists()).unwrap_or(false) { return meta; } - warn!("VOXYGEN_CONFIG points to invalid path."); + warn!(?path, "VOXYGEN_CONFIG points to invalid path."); } let proj_dirs = ProjectDirs::from("net", "veloren", "voxygen") diff --git a/voxygen/src/profile.rs b/voxygen/src/profile.rs index bdfd8c5386..75d6ee9573 100644 --- a/voxygen/src/profile.rs +++ b/voxygen/src/profile.rs @@ -66,13 +66,14 @@ impl Profile { Ok(profile) => return profile, Err(e) => { warn!( - "Failed to parse profile file! Falling back to default. {}", - e + ?e, + ?path, + "Failed to parse profile file! Falling back to default." ); // Rename the corrupted profile file. let new_path = path.with_extension("invalid.ron"); - if let Err(err) = std::fs::rename(path, new_path) { - warn!("Failed to rename profile file. {}", err); + if let Err(e) = std::fs::rename(path.clone(), new_path.clone()) { + warn!(?e, ?path, ?new_path, "Failed to rename profile file."); } }, } @@ -87,8 +88,8 @@ impl Profile { /// Save the current profile to disk, warn on failure. pub fn save_to_file_warn(&self) { - if let Err(err) = self.save_to_file() { - warn!("Failed to save profile: {:?}", err); + if let Err(e) = self.save_to_file() { + warn!(?e, "Failed to save profile"); } } @@ -156,12 +157,12 @@ impl Profile { } fn get_path() -> PathBuf { - if let Some(val) = std::env::var_os("VOXYGEN_CONFIG") { - let profile = PathBuf::from(val).join("profile.ron"); + if let Some(path) = std::env::var_os("VOXYGEN_CONFIG") { + let profile = PathBuf::from(path.clone()).join("profile.ron"); if profile.exists() || profile.parent().map(|x| x.exists()).unwrap_or(false) { return profile; } - warn!("VOXYGEN_CONFIG points to invalid path."); + warn!(?path, "VOXYGEN_CONFIG points to invalid path."); } let proj_dirs = ProjectDirs::from("net", "veloren", "voxygen") diff --git a/voxygen/src/render/renderer.rs b/voxygen/src/render/renderer.rs index 4d471b2f58..a6e37ff192 100644 --- a/voxygen/src/render/renderer.rs +++ b/voxygen/src/render/renderer.rs @@ -354,10 +354,7 @@ impl Renderer { self.postprocess_pipeline = postprocess_pipeline; self.player_shadow_pipeline = player_shadow_pipeline; }, - Err(e) => error!( - "Could not recreate shaders from assets due to an error: {:#?}", - e - ), + Err(e) => error!(?e, "Could not recreate shaders from assets due to an error",), } } diff --git a/voxygen/src/scene/figure/load.rs b/voxygen/src/scene/figure/load.rs index 5ca885024a..08c920775f 100644 --- a/voxygen/src/scene/figure/load.rs +++ b/voxygen/src/scene/figure/load.rs @@ -38,7 +38,7 @@ fn graceful_load_vox(mesh_name: &str) -> Arc { match assets::load::(full_specifier.as_str()) { Ok(dot_vox) => dot_vox, Err(_) => { - error!("Could not load vox file for figure: {}", full_specifier); + error!(?full_specifier, "Could not load vox file for figure"); assets::load_expect::("voxygen.voxel.not_found") }, } @@ -157,8 +157,9 @@ impl HumHeadSpec { Some(spec) => spec, None => { error!( - "No head specification exists for the combination of {:?} and {:?}", - body.species, body.body_type + ?body.species, + ?body.body_type, + "No head specification exists for the combination of species and body" ); return load_mesh("not_found", Vec3::new(-5.0, -5.0, -2.5), generate_mesh); }, @@ -368,7 +369,7 @@ impl HumArmorShoulderSpec { match self.0.map.get(&shoulder) { Some(spec) => spec, None => { - error!("No shoulder specification exists for {:?}", shoulder); + error!(?shoulder, "No shoulder specification exists"); return load_mesh("not_found", Vec3::new(-3.0, -3.5, 0.1), generate_mesh); }, } @@ -450,7 +451,7 @@ impl HumArmorChestSpec { match self.0.map.get(&chest) { Some(spec) => spec, None => { - error!("No chest specification exists for {:?}", loadout.chest); + error!(?loadout.chest, "No chest specification exists"); return load_mesh("not_found", Vec3::new(-7.0, -3.5, 2.0), generate_mesh); }, } @@ -507,7 +508,7 @@ impl HumArmorHandSpec { match self.0.map.get(&hand) { Some(spec) => spec, None => { - error!("No hand specification exists for {:?}", hand); + error!(?hand, "No hand specification exists"); return load_mesh("not_found", Vec3::new(-1.5, -1.5, -7.0), generate_mesh); }, } @@ -583,7 +584,7 @@ impl HumArmorBeltSpec { match self.0.map.get(&belt) { Some(spec) => spec, None => { - error!("No belt specification exists for {:?}", belt); + error!(?belt, "No belt specification exists"); return load_mesh("not_found", Vec3::new(-4.0, -3.5, 2.0), generate_mesh); }, } @@ -627,7 +628,7 @@ impl HumArmorBackSpec { match self.0.map.get(&back) { Some(spec) => spec, None => { - error!("No back specification exists for {:?}", back); + error!(?back, "No back specification exists"); return load_mesh("not_found", Vec3::new(-4.0, -3.5, 2.0), generate_mesh); }, } @@ -670,7 +671,7 @@ impl HumArmorPantsSpec { match self.0.map.get(&pants) { Some(spec) => spec, None => { - error!("No pants specification exists for {:?}", pants); + error!(?pants, "No pants specification exists"); return load_mesh("not_found", Vec3::new(-5.0, -3.5, 1.0), generate_mesh); }, } @@ -727,7 +728,7 @@ impl HumArmorFootSpec { match self.0.map.get(&foot) { Some(spec) => spec, None => { - error!("No foot specification exists for {:?}", foot); + error!(?foot, "No foot specification exists"); return load_mesh("not_found", Vec3::new(-2.5, -3.5, -9.0), generate_mesh); }, } @@ -793,7 +794,7 @@ impl HumMainWeaponSpec { let spec = match self.0.get(tool_kind) { Some(spec) => spec, None => { - error!("No tool/weapon specification exists for {:?}", tool_kind); + error!(?tool_kind, "No tool/weapon specification exists"); return load_mesh("not_found", Vec3::new(-1.5, -1.5, -7.0), generate_mesh); }, }; @@ -820,7 +821,7 @@ impl HumArmorLanternSpec { match self.0.map.get(&kind) { Some(spec) => spec, None => { - error!("No lantern specification exists for {:?}", kind); + error!(?kind, "No lantern specification exists"); return load_mesh("not_found", Vec3::new(-4.0, -3.5, 2.0), generate_mesh); }, } @@ -863,7 +864,7 @@ impl HumArmorHeadSpec { match self.0.map.get(&head) { Some(spec) => spec, None => { - error!("No head specification exists for {:?}", head); + error!(?head, "No head specification exists"); return load_mesh("not_found", Vec3::new(-5.0, -3.5, 1.0), generate_mesh); }, } @@ -918,7 +919,7 @@ impl HumArmorTabardSpec { match self.0.map.get(&tabard) { Some(spec) => spec, None => { - error!("No tabard specification exists for {:?}", tabard); + error!(?tabard, "No tabard specification exists"); return load_mesh("not_found", Vec3::new(-5.0, -3.5, 1.0), generate_mesh); }, } diff --git a/voxygen/src/scene/simple.rs b/voxygen/src/scene/simple.rs index e210493bef..3988e64739 100644 --- a/voxygen/src/scene/simple.rs +++ b/voxygen/src/scene/simple.rs @@ -169,7 +169,7 @@ impl Scene { } = self.camera.dependents(); const VD: f32 = 115.0; // View Distance const TIME: f64 = 43200.0; // 12 hours*3600 seconds - if let Err(err) = renderer.update_consts(&mut self.globals, &[Globals::new( + if let Err(e) = renderer.update_consts(&mut self.globals, &[Globals::new( view_mat, proj_mat, cam_pos, @@ -186,7 +186,7 @@ impl Scene { self.camera.get_mode(), 250.0, )]) { - error!("Renderer failed to update: {:?}", err); + error!(?e, "Renderer failed to update"); } self.figure_model_cache.clean(scene_data.tick); diff --git a/voxygen/src/settings.rs b/voxygen/src/settings.rs index ef16948655..f496c0c23c 100644 --- a/voxygen/src/settings.rs +++ b/voxygen/src/settings.rs @@ -718,13 +718,13 @@ impl Settings { match ron::de::from_reader(file) { Ok(s) => return s, Err(e) => { - warn!("Failed to parse setting file! Fallback to default. {}", e); + warn!(?e, "Failed to parse setting file! Fallback to default."); // Rename the corrupted settings file let mut new_path = path.to_owned(); new_path.pop(); new_path.push("settings.invalid.ron"); - if let Err(err) = std::fs::rename(path, new_path) { - warn!("Failed to rename settings file. {}", err); + if let Err(e) = std::fs::rename(path.clone(), new_path.clone()) { + warn!(?e, ?path, ?new_path, "Failed to rename settings file."); } }, } @@ -738,8 +738,8 @@ impl Settings { } pub fn save_to_file_warn(&self) { - if let Err(err) = self.save_to_file() { - warn!("Failed to save settings: {:?}", err); + if let Err(e) = self.save_to_file() { + warn!(?e, "Failed to save settings"); } } @@ -756,12 +756,12 @@ impl Settings { } pub fn get_settings_path() -> PathBuf { - if let Some(val) = std::env::var_os("VOXYGEN_CONFIG") { - let settings = PathBuf::from(val).join("settings.ron"); + if let Some(path) = std::env::var_os("VOXYGEN_CONFIG") { + let settings = PathBuf::from(path.clone()).join("settings.ron"); if settings.exists() || settings.parent().map(|x| x.exists()).unwrap_or(false) { return settings; } - warn!("VOXYGEN_CONFIG points to invalid path."); + warn!(?path, "VOXYGEN_CONFIG points to invalid path."); } let proj_dirs = ProjectDirs::from("net", "veloren", "voxygen") diff --git a/voxygen/src/ui/graphic/mod.rs b/voxygen/src/ui/graphic/mod.rs index 78c534036e..aa696be782 100644 --- a/voxygen/src/ui/graphic/mod.rs +++ b/voxygen/src/ui/graphic/mod.rs @@ -43,7 +43,7 @@ const ATLAS_CUTTOFF_FRAC: f32 = 0.2; /// Multiplied by current window size const GRAPHIC_CACHE_RELATIVE_SIZE: u16 = 1; -#[derive(PartialEq, Eq, Hash, Copy, Clone)] +#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] pub struct Id(u32); // TODO these can become invalid when clearing the cache @@ -300,7 +300,10 @@ fn draw_graphic(graphic_map: &GraphicMap, graphic_id: Id, dims: Vec2) -> Op *sample_strat, )), None => { - warn!("A graphic was requested via an id which is not in use"); + warn!( + ?graphic_id, + "A graphic was requested via an id which is not in use" + ); None }, } @@ -333,12 +336,12 @@ fn aabr_from_alloc_rect(rect: guillotiere::Rectangle) -> Aabr { fn upload_image(renderer: &mut Renderer, aabr: Aabr, tex: &Texture, image: &RgbaImage) { let offset = aabr.min.into_array(); let size = aabr.size().into_array(); - if let Err(err) = renderer.update_texture( + if let Err(e) = renderer.update_texture( tex, offset, size, &image.pixels().map(|p| p.0).collect::>(), ) { - warn!("Failed to update texture: {:?}", err); + warn!(?e, "Failed to update texture"); } } diff --git a/voxygen/src/window.rs b/voxygen/src/window.rs index e8740663de..7603b02bf4 100644 --- a/voxygen/src/window.rs +++ b/voxygen/src/window.rs @@ -443,11 +443,11 @@ impl Window { ); None }, - Err(gilrs::Error::Other(err)) => { + Err(gilrs::Error::Other(e)) => { error!( - "Platform-specific error when creating a Gilrs instance: `{}`. Falling back \ - to no controller support.", - err + ?e, + "Platform-specific error when creating a Gilrs instance. Falling back to no \ + controller support." ); None }, @@ -962,8 +962,8 @@ impl Window { use std::time::SystemTime; // Check if folder exists and create it if it does not if !path.exists() { - if let Err(err) = std::fs::create_dir_all(&path) { - warn!("Couldn't create folder for screenshot: {:?}", err); + if let Err(e) = std::fs::create_dir_all(&path) { + warn!(?e, "Couldn't create folder for screenshot"); let _result = sender.send(String::from("Couldn't create folder for screenshot")); } @@ -975,8 +975,8 @@ impl Window { .map(|d| d.as_millis()) .unwrap_or(0) )); - if let Err(err) = img.save(&path) { - warn!("Couldn't save screenshot: {:?}", err); + if let Err(e) = img.save(&path) { + warn!(?e, "Couldn't save screenshot"); let _result = sender.send(String::from("Couldn't save screenshot")); } else { let _result = @@ -984,10 +984,7 @@ impl Window { } }); }, - Err(err) => error!( - "Couldn't create screenshot due to renderer error: {:?}", - err - ), + Err(e) => error!(?e, "Couldn't create screenshot due to renderer error"), } } diff --git a/world/Cargo.toml b/world/Cargo.toml index 9601d5b5f8..90b58e4528 100644 --- a/world/Cargo.toml +++ b/world/Cargo.toml @@ -17,7 +17,7 @@ num = "0.2.0" ordered-float = "1.0" hashbrown = { version = "0.6", features = ["rayon", "serde", "nightly"] } lazy_static = "1.4.0" -tracing = { version = "0.1", default-features = false , features = ["attributes"] } +tracing = { version = "0.1", default-features = false } rand = "0.7" rand_chacha = "0.2.1" arr_macro = "0.1.2" diff --git a/world/examples/water.rs b/world/examples/water.rs index 1ac35361e5..1b1c47354f 100644 --- a/world/examples/water.rs +++ b/world/examples/water.rs @@ -114,8 +114,8 @@ fn main() { .expect("Image dimensions must be valid"); let mut path = PathBuf::from("./screenshots"); if !path.exists() { - if let Err(err) = std::fs::create_dir(&path) { - warn!("Couldn't create folder for screenshot: {:?}", err); + if let Err(e) = std::fs::create_dir(&path) { + warn!(?e, ?path, "Couldn't create folder for screenshot"); } } path.push(format!( @@ -125,8 +125,8 @@ fn main() { .map(|d| d.as_millis()) .unwrap_or(0) )); - if let Err(err) = world_map.save(&path) { - warn!("Couldn't save screenshot: {:?}", err); + if let Err(e) = world_map.save(&path) { + warn!(?e, ?path, "Couldn't save screenshot"); } } } diff --git a/world/src/civ/mod.rs b/world/src/civ/mod.rs index efeaffa9d9..2a5998f5b8 100644 --- a/world/src/civ/mod.rs +++ b/world/src/civ/mod.rs @@ -187,7 +187,7 @@ impl Civs { .get_mut(pos) .map(|chunk| chunk.sites.push(world_site.clone())); } - info!("Placed site at {:?}", site.center); + info!(?site.center, "Placed site at location"); } //this.display_info(); diff --git a/world/src/column/mod.rs b/world/src/column/mod.rs index f7fb19161f..f587ceba86 100644 --- a/world/src/column/mod.rs +++ b/world/src/column/mod.rs @@ -214,7 +214,7 @@ impl<'a> Sampler<'a> for ColumnGen<'a> { } else { match kind { RiverKind::River { .. } => { - error!("What? River: {:?}, Pos: {:?}", river, posj); + error!(?river, ?posj, "What?"); panic!("How can a river have no downhill?"); }, RiverKind::Lake { .. } => { @@ -619,8 +619,10 @@ impl<'a> Sampler<'a> for ColumnGen<'a> { dist } else { error!( - "Ocean: {:?} Here: {:?}, Ocean: {:?}", - max_border_river, chunk_pos, max_border_river_pos + ?max_border_river, + ?chunk_pos, + ?max_border_river_pos, + "downhill error details" ); panic!( "Oceans should definitely have a downhill! \ diff --git a/world/src/sim/erosion.rs b/world/src/sim/erosion.rs index 787c75a45b..d1deccd414 100644 --- a/world/src/sim/erosion.rs +++ b/world/src/sim/erosion.rs @@ -724,7 +724,7 @@ fn erode( // NOTE: The value being divided by here sets the effective maximum uplift rate, // as everything is scaled to it! let dt = max_uplift as f64 / 1e-3; - debug!("dt={:?}", dt); + debug!(?dt, ""); // Minimum sediment thickness before we treat erosion as sediment based. let sediment_thickness = |_n| /*6.25e-5*/1.0e-4 * dt; let neighbor_coef = TerrainChunkSize::RECT_SIZE.map(|e| e as f64); diff --git a/world/src/sim/mod.rs b/world/src/sim/mod.rs index 81126c2171..67d5d57e14 100644 --- a/world/src/sim/mod.rs +++ b/world/src/sim/mod.rs @@ -877,8 +877,8 @@ impl WorldSim { FileOpts::LoadLegacy(ref path) => { let file = match File::open(path) { Ok(file) => file, - Err(err) => { - warn!("Couldn't read path for maps: {:?}", err); + Err(e) => { + warn!(?e, ?path, "Couldn't read path for maps"); return None; }, }; @@ -886,11 +886,11 @@ impl WorldSim { let reader = BufReader::new(file); let map: WorldFileLegacy = match bincode::deserialize_from(reader) { Ok(map) => map, - Err(err) => { + Err(e) => { warn!( - "Couldn't parse legacy map: {:?}). Maybe you meant to try a \ - regular load?", - err + ?e, + "Couldn't parse legacy map. Maybe you meant to try a regular \ + load?" ); return None; }, @@ -901,8 +901,8 @@ impl WorldSim { FileOpts::Load(ref path) => { let file = match File::open(path) { Ok(file) => file, - Err(err) => { - warn!("Couldn't read path for maps: {:?}", err); + Err(e) => { + warn!(?e, ?path, "Couldn't read path for maps"); return None; }, }; @@ -910,11 +910,10 @@ impl WorldSim { let reader = BufReader::new(file); let map: WorldFile = match bincode::deserialize_from(reader) { Ok(map) => map, - Err(err) => { + Err(e) => { warn!( - "Couldn't parse modern map: {:?}). Maybe you meant to try a \ - legacy load?", - err + ?e, + "Couldn't parse modern map. Maybe you meant to try a legacy load?" ); return None; }, @@ -925,22 +924,18 @@ impl WorldSim { FileOpts::LoadAsset(ref specifier) => { let reader = match assets::load_file(specifier, &["bin"]) { Ok(reader) => reader, - Err(err) => { - warn!( - "Couldn't read asset specifier {:?} for maps: {:?}", - specifier, err - ); + Err(e) => { + warn!(?e, ?specifier, "Couldn't read asset specifier for maps",); return None; }, }; let map: WorldFile = match bincode::deserialize_from(reader) { Ok(map) => map, - Err(err) => { + Err(e) => { warn!( - "Couldn't parse modern map: {:?}). Maybe you meant to try a \ - legacy load?", - err + ?e, + "Couldn't parse modern map. Maybe you meant to try a legacy load?" ); return None; }, @@ -1026,8 +1021,8 @@ impl WorldSim { // Check if folder exists and create it if it does not let mut path = PathBuf::from("./maps"); if !path.exists() { - if let Err(err) = std::fs::create_dir(&path) { - warn!("Couldn't create folder for map: {:?}", err); + if let Err(e) = std::fs::create_dir(&path) { + warn!(?e, ?path, "Couldn't create folder for map"); return; } } @@ -1039,17 +1034,17 @@ impl WorldSim { .map(|d| d.as_millis()) .unwrap_or(0) )); - let file = match File::create(path) { + let file = match File::create(path.clone()) { Ok(file) => file, - Err(err) => { - warn!("Couldn't create file for maps: {:?}", err); + Err(e) => { + warn!(?e, ?path, "Couldn't create file for maps"); return; }, }; let writer = BufWriter::new(file); - if let Err(err) = bincode::serialize_into(writer, &map) { - warn!("Couldn't write map: {:?}", err); + if let Err(e) = bincode::serialize_into(writer, &map) { + warn!(?e, "Couldn't write map"); } } })(); @@ -1088,7 +1083,7 @@ impl WorldSim { let is_ocean_fn = |posi: usize| is_ocean[posi]; let mut dh = downhill(|posi| alt[posi], is_ocean_fn); let (boundary_len, indirection, water_alt_pos, maxh) = get_lakes(|posi| alt[posi], &mut dh); - debug!("Max height: {:?}", maxh); + debug!(?maxh, "Max height"); let (mrec, mstack, mwrec) = { let mut wh = vec![0.0; WORLD_SIZE.x * WORLD_SIZE.y]; get_multi_rec( @@ -1911,10 +1906,9 @@ impl SimChunk { ); */ } if river_slope.abs() >= 0.25 && cross_section.x >= 1.0 { - debug!( - "Big waterfall! Pos area: {:?}, River data: {:?}, slope: {:?}", - wposf, river, river_slope - ); + let pos_area = wposf; + let river_data = &river; + debug!(?pos_area, ?river_data, ?river_slope, "Big waterfall!",); } }, Some(RiverKind::Lake { .. }) => {