From 92e65498532129f721067662602215e8057a9d04 Mon Sep 17 00:00:00 2001 From: Jannify Date: Fri, 29 May 2020 09:06:12 +0200 Subject: [PATCH] Use Nlog logging * #913 Added NLog and supporting instance class * #913 shifted classes and added async calling on logging file * #913 added all interface methods and implemetations for logger * #913 added config file for NLog with formatting * #913 Removed old log error method and replaced it with new one * #913 changed warnings, trace and error * #913 updated all the debug instances * #913 removed old logger class * #913 Renamed log class and removed log4net * #913 quick changes after reviewing my own pull request and reading the submission guidelines * #913 Updated some thing to actually match the acceptance of the ticket :facepalm: * #913 Changed log back to static class and split out methods * #913 PR changes to move the nlog config to a more global place and removed the enum for catogorey * #913 PR Fixes * Fix build errors, review changes * Copy nlog config to subnautica directory * Use rolling log file, archived per day * Use colored console * Review changes * Configure nlog programmatically * Made changes to logging so that it's similar as before * Added InGame logging through NLog Changed a lot of logs to structured logging * Fixed logs that were used improperly due to changes * Set player name to log context on session joined * Dont use space before log message when player name is not set * Using AsyncTargetWrapper for the log file target * Set DetectConsoleAvailable to true * Fixed sensitive logging not working due to logger name change * Moved when player name is set in logger to earlier moment * Add Init submodules to buildingPullRequest.yml * - Remove log4net - Remove double log output of the admin password * > Changed log messages that don't need structural logging > Removed structural logging from non sensitive log methods * Merge branch 'master' Conflicts: NitroxClient/GameLogic/InitialSync/PdaInitialSyncProcessor.cs NitroxLauncher/LauncherLogic.cs NitroxLauncher/NitroxLauncher.csproj NitroxModel/Logger/Log.cs NitroxModel/NitroxModel.csproj NitroxModel/Packets/Packet.cs NitroxPatcher/Main.cs NitroxServer-Subnautica/Program.cs NitroxServer/Serialization/World/WorldPersistence.cs --- .../MultiplayerSessionManager.cs | 7 +- .../Processors/InitialPlayerSyncProcessor.cs | 6 +- .../InventoryItemsInitialSyncProcessor.cs | 10 +- .../InitialSync/PdaInitialSyncProcessor.cs | 14 +- .../StorageSlotsInitialSyncProcessor.cs | 4 +- NitroxClient/GameLogic/ItemContainers.cs | 14 +- NitroxClient/GameLogic/NitroxConsole.cs | 2 +- .../Spawning/SerializedEntitySpawner.cs | 4 +- NitroxClient/GameLogic/Vehicles.cs | 4 +- .../MonoBehaviours/Gui/MainMenu/JoinServer.cs | 9 +- .../Gui/MainMenu/MainMenuMultiplayerPanel.cs | 4 +- NitroxClient/MonoBehaviours/Multiplayer.cs | 7 +- .../MonoBehaviours/NitroxBootstrapper.cs | 2 +- .../MonoBehaviours/NitroxDebugManager.cs | 6 +- NitroxClient/MonoBehaviours/PowerMonitor.cs | 2 +- NitroxClient/Unity/Helper/DebugUtils.cs | 4 +- NitroxLauncher/App.xaml.cs | 5 +- .../Logger/SubnauticaInGameLogger.cs | 9 +- NitroxModel/Logger/InGameLogger.cs | 3 +- NitroxModel/Logger/Log.cs | 301 ++++++++++++------ NitroxModel/NitroxModel.csproj | 17 +- NitroxModel/Packets/Packet.cs | 23 +- NitroxModel/Server/ServerConfigItem.cs | 4 +- NitroxModel/packages.config | 2 +- NitroxPatcher/Main.cs | 14 +- NitroxServer-Subnautica/Program.cs | 7 +- .../Communication/Packets/PacketHandler.cs | 3 +- .../SubRootChangedPacketProcessor.cs | 2 +- .../Processors/VehicleAddPacketProcessor.cs | 2 +- .../Processors/VehicleColorChangeProcessor.cs | 2 +- .../Processors/VehicleDockingProcessor.cs | 2 +- .../ConsoleCommands/Abstract/Command.cs | 8 +- .../ChangeAdminPasswordCommand.cs | 2 +- .../ChangeServerPasswordCommand.cs | 2 +- .../GameLogic/Items/InventoryManager.cs | 2 +- NitroxServer/GameLogic/TimeKeeper.cs | 4 +- NitroxServer/IpLogger.cs | 8 +- NitroxServer/NitroxServer.csproj | 2 +- .../Serialization/BatchCellsParser.cs | 1 - .../Serialization/ServerJsonSerializer.cs | 2 +- .../Serialization/ServerProtoBufSerializer.cs | 2 +- .../Serialization/World/WorldPersistence.cs | 4 +- 42 files changed, 323 insertions(+), 209 deletions(-) diff --git a/NitroxClient/Communication/MultiplayerSession/MultiplayerSessionManager.cs b/NitroxClient/Communication/MultiplayerSession/MultiplayerSessionManager.cs index 3bf6adac56..735088bc9d 100644 --- a/NitroxClient/Communication/MultiplayerSession/MultiplayerSessionManager.cs +++ b/NitroxClient/Communication/MultiplayerSession/MultiplayerSessionManager.cs @@ -117,12 +117,17 @@ public void UpdateConnectionState(IMultiplayerSessionConnectionState sessionConn string fromStage = CurrentState == null ? "null" : CurrentState.CurrentStage.ToString(); string username = AuthenticationContext == null ? "" : AuthenticationContext.Username; - Log.Info($"Updating session stage from '{fromStage}' to '{sessionConnectionState.CurrentStage}' for '{username}'"); + Log.Debug($"Updating session stage from '{fromStage}' to '{sessionConnectionState.CurrentStage}' for '{username}'"); CurrentState = sessionConnectionState; // Last connection state changed will not have any handlers ConnectionStateChanged?.Invoke(CurrentState); + + if (sessionConnectionState.CurrentStage == MultiplayerSessionConnectionStage.SESSION_RESERVED) + { + Log.PlayerName = username; + } } public void ClearSessionState() diff --git a/NitroxClient/Communication/Packets/Processors/InitialPlayerSyncProcessor.cs b/NitroxClient/Communication/Packets/Processors/InitialPlayerSyncProcessor.cs index 612bbbb2a6..9f275bf9a5 100644 --- a/NitroxClient/Communication/Packets/Processors/InitialPlayerSyncProcessor.cs +++ b/NitroxClient/Communication/Packets/Processors/InitialPlayerSyncProcessor.cs @@ -36,7 +36,7 @@ public override void Process(InitialPlayerSync packet) cumulativeProcessorsRan = 0; Multiplayer.Main.StartCoroutine(ProcessInitialSyncPacket(this, null)); } - + private IEnumerator ProcessInitialSyncPacket(object sender, EventArgs eventArgs) { // Some packets should not fire during game session join but only afterwards so that initialized/spawned game objects don't trigger packet sending again. @@ -46,7 +46,7 @@ private IEnumerator ProcessInitialSyncPacket(object sender, EventArgs eventArgs) do { yield return Multiplayer.Main.StartCoroutine(RunPendingProcessors()); - + moreProcessorsToRun = alreadyRan.Count < processors.Count; if (moreProcessorsToRun && processorsRanLastCycle == 0) { @@ -80,7 +80,7 @@ private IEnumerator RunPendingProcessors() } } } - + private bool HasDependenciesSatisfied(InitialSyncProcessor processor) { foreach (Type dependentType in processor.DependentProcessors) diff --git a/NitroxClient/GameLogic/InitialSync/InventoryItemsInitialSyncProcessor.cs b/NitroxClient/GameLogic/InitialSync/InventoryItemsInitialSyncProcessor.cs index e9652dcf36..aec7d6949f 100644 --- a/NitroxClient/GameLogic/InitialSync/InventoryItemsInitialSyncProcessor.cs +++ b/NitroxClient/GameLogic/InitialSync/InventoryItemsInitialSyncProcessor.cs @@ -51,12 +51,12 @@ public override IEnumerator Process(InitialPlayerSync packet, WaitScreen.ManualW } catch (Exception ex) { - Log.Error("Error deserializing item data " + itemdata.ItemId + " " + ex.Message); + Log.Error(ex, $"Error deserializing item data. Id: {itemdata.ItemId}"); continue; } - Log.Info("Initial item data for " + item.name + " giving to container " + itemdata.ContainerId); - + Log.Debug($"Initial item data for {item.name} giving to container {itemdata.ContainerId}"); + Pickupable pickupable = item.GetComponent(); if (pickupable != null && itemdata.ContainerId == packet.PlayerGameObjectId) @@ -79,8 +79,8 @@ public override IEnumerator Process(InitialPlayerSync packet, WaitScreen.ManualW yield return null; } } - - Log.Info("Recieved initial sync with " + totalItemDataSynced + " inventory items"); + + Log.Info($"Received initial sync with {totalItemDataSynced} inventory items"); } } } diff --git a/NitroxClient/GameLogic/InitialSync/PdaInitialSyncProcessor.cs b/NitroxClient/GameLogic/InitialSync/PdaInitialSyncProcessor.cs index 05bc3ee048..878dba00e0 100644 --- a/NitroxClient/GameLogic/InitialSync/PdaInitialSyncProcessor.cs +++ b/NitroxClient/GameLogic/InitialSync/PdaInitialSyncProcessor.cs @@ -43,10 +43,10 @@ public override IEnumerator Process(InitialPlayerSync packet, WaitScreen.ManualW waitScreenItem.SetProgress(1f); yield return null; } - + private void SetEncyclopediaEntry(List entries) { - Log.Info("Received initial sync packet with " + entries.Count + " encyclopedia entries"); + Log.Info($"Received initial sync packet with {entries.Count} encyclopedia entries"); using (packetSender.Suppress()) { @@ -66,7 +66,7 @@ private void SetPDAEntryComplete(List pdaEntryComplete) complete.Add(item.ToUnity()); } - Log.Info("PDAEntryComplete Save:" + pdaEntryComplete.Count + " Read Partial Client Final Count:" + complete.Count); + Log.Info($"PDAEntryComplete: New added: {pdaEntryComplete.Count}, Total: {complete.Count}"); } @@ -79,12 +79,12 @@ private void SetPDAEntryPartial(List entries) partial.Add(new PDAScanner.Entry { progress = entry.Progress, techType = entry.TechType.ToUnity(), unlocked = entry.Unlocked }); } - Log.Info("PDAEntryPartial Save :" + entries.Count + " Read Partial Client Final Count:" + partial.Count); + Log.Debug($"PDAEntryPartial: New added: {entries.Count}, Total: {partial.Count}"); } - + private void SetKnownTech(List techTypes) { - Log.Info("Received initial sync packet with " + techTypes.Count + " known tech types"); + Log.Info($"Received initial sync packet with {techTypes.Count} known tech types"); using (packetSender.Suppress()) { @@ -98,7 +98,7 @@ private void SetKnownTech(List techTypes) private void SetPDALog(List logEntries) { - Log.Info("Received initial sync packet with " + logEntries.Count + " pda log entries"); + Log.Info($"Received initial sync packet with {logEntries.Count} pda log entries"); using (packetSender.Suppress()) { diff --git a/NitroxClient/GameLogic/InitialSync/StorageSlotsInitialSyncProcessor.cs b/NitroxClient/GameLogic/InitialSync/StorageSlotsInitialSyncProcessor.cs index 42ebc339a0..62dec5a603 100644 --- a/NitroxClient/GameLogic/InitialSync/StorageSlotsInitialSyncProcessor.cs +++ b/NitroxClient/GameLogic/InitialSync/StorageSlotsInitialSyncProcessor.cs @@ -33,14 +33,14 @@ public override IEnumerator Process(InitialPlayerSync packet, WaitScreen.ManualW int storageSlotsSynced = 0; using (packetSender.Suppress()) - { + { foreach (ItemData itemData in packet.StorageSlots) { waitScreenItem.SetProgress(storageSlotsSynced, packet.StorageSlots.Count); GameObject item = SerializationHelper.GetGameObject(itemData.SerializedData); - Log.Info("Initial StorageSlot item data for " + item.name + " giving to container " + itemData.ContainerId); + Log.Debug($"Initial StorageSlot item data for {item.name} giving to container {itemData.ContainerId}"); NitroxEntity.SetNewId(item, itemData.ItemId); slots.AddItem(item, itemData.ContainerId, true); diff --git a/NitroxClient/GameLogic/ItemContainers.cs b/NitroxClient/GameLogic/ItemContainers.cs index e83b75cda5..e8e3e8999d 100644 --- a/NitroxClient/GameLogic/ItemContainers.cs +++ b/NitroxClient/GameLogic/ItemContainers.cs @@ -30,7 +30,7 @@ public void BroadcastItemAdd(Pickupable pickupable, Transform containerTransform ItemData itemData = new ItemData(GetOwner(containerTransform), itemId, bytes); if (packetSender.Send(new ItemContainerAdd(itemData))) { - Log.Debug($"Sent: Added item '{pickupable.GetTechType()}' to container '{containerTransform.gameObject.GetHierarchyPath()}'"); + Log.Debug($"Sent: Added item {pickupable.GetTechType()} to container {containerTransform.gameObject.GetHierarchyPath()}"); } } @@ -39,7 +39,7 @@ public void BroadcastItemRemoval(Pickupable pickupable, Transform containerTrans NitroxId itemId = NitroxEntity.GetId(pickupable.gameObject); if (packetSender.Send(new ItemContainerRemove(GetOwner(containerTransform), itemId))) { - Log.Debug($"Sent: removed item '{pickupable.GetTechType()}' from container '{containerTransform.gameObject.GetHierarchyPath()}'"); + Log.Debug($"Sent: Removed item {pickupable.GetTechType()} from container {containerTransform.gameObject.GetHierarchyPath()}"); } } @@ -48,13 +48,13 @@ public void AddItem(GameObject item, NitroxId containerId) Optional owner = NitroxEntity.GetObjectFrom(containerId); if (!owner.HasValue) { - Log.Error("Unable to find inventory container with id: " + containerId); + Log.Error($"Unable to find inventory container with id {containerId}"); return; } Optional opContainer = InventoryContainerHelper.GetBasedOnOwnersType(owner.Value); if (!opContainer.HasValue) { - Log.Error("Could not find container field on object " + owner.Value.name); + Log.Error($"Could not find container field on GameObject {owner.Value.GetHierarchyPath()}"); return; } @@ -73,7 +73,7 @@ public void RemoveItem(NitroxId ownerId, NitroxId itemId) Optional opContainer = InventoryContainerHelper.GetBasedOnOwnersType(owner); if (!opContainer.HasValue) { - Log.Error($"Could not find item container behaviour on object '{owner.name}' with Nitrox id '{ownerId}'"); + Log.Error($"Could not find item container behaviour on object {owner.GetHierarchyPath()} with id {ownerId}"); return; } @@ -96,9 +96,9 @@ public NitroxId GetCyclopsLockerId(Transform ownerTransform) StorageContainer storageContainer = locker.GetComponentInChildren(); if (!storageContainer) { - throw new Exception($"Could not find {nameof(StorageContainer)} From Object: submarine_locker_01_0{LockerId}"); + throw new Exception($"Could not find {nameof(StorageContainer)} From Object: submarine_locker_01_0{LockerId}"); } - + return NitroxEntity.GetId(storageContainer.gameObject); } diff --git a/NitroxClient/GameLogic/NitroxConsole.cs b/NitroxClient/GameLogic/NitroxConsole.cs index 4d0eeef27e..17d6fa4156 100644 --- a/NitroxClient/GameLogic/NitroxConsole.cs +++ b/NitroxClient/GameLogic/NitroxConsole.cs @@ -45,7 +45,7 @@ public void Spawn(GameObject gameObject) } catch (Exception ex) { - Log.Error($"Error while trying to spawn \"{techType}\" from devconsole", ex); + Log.Error(ex, $"Error while trying to spawn {techType} from devconsole"); } } diff --git a/NitroxClient/GameLogic/Spawning/SerializedEntitySpawner.cs b/NitroxClient/GameLogic/Spawning/SerializedEntitySpawner.cs index b463e782a3..e02a497189 100644 --- a/NitroxClient/GameLogic/Spawning/SerializedEntitySpawner.cs +++ b/NitroxClient/GameLogic/Spawning/SerializedEntitySpawner.cs @@ -46,7 +46,7 @@ public bool SpawnsOwnChildren() { return false; } - + private void EnableRigidBody(GameObject gameObject) { Rigidbody rigidBody = gameObject.RequireComponent(); @@ -67,7 +67,7 @@ private void AssignToWaterPark(GameObject gameObject, NitroxId waterParkId) private void ExecuteDropItemAction(TechType techType, GameObject gameObject) { - Log.Debug("Performing drop action for tech type: " + techType); + Log.Debug($"Performing drop action for tech type {techType}"); ItemDropAction itemDropAction = ItemDropAction.FromTechType(techType); itemDropAction.ProcessDroppedItem(gameObject); diff --git a/NitroxClient/GameLogic/Vehicles.cs b/NitroxClient/GameLogic/Vehicles.cs index 044f0c702a..374aa5c61e 100644 --- a/NitroxClient/GameLogic/Vehicles.cs +++ b/NitroxClient/GameLogic/Vehicles.cs @@ -92,7 +92,7 @@ public VehicleModel BuildVehicleModelFrom(GameObject gameObject, TechType techTy } catch (Exception ex) { - Log.Error($"{nameof(Vehicles)}: Error while trying to spawn a cyclops ({constructedObjectId})", ex); + Log.Error(ex, $"{nameof(Vehicles)}: Error while trying to spawn a cyclops. Id: {constructedObjectId}"); } } @@ -178,7 +178,7 @@ public void CreateVehicle(TechType techType, NitroxId id, Vector3 position, Quat } catch (Exception ex) { - Log.Error($"{nameof(Vehicles)}: Error while creating a vehicle {techType} {id}", ex); + Log.Error(ex, $"{nameof(Vehicles)}: Error while creating a vehicle. TechType: {techType} Id: {id}"); } } diff --git a/NitroxClient/MonoBehaviours/Gui/MainMenu/JoinServer.cs b/NitroxClient/MonoBehaviours/Gui/MainMenu/JoinServer.cs index da26ab0872..c86d6034ba 100644 --- a/NitroxClient/MonoBehaviours/Gui/MainMenu/JoinServer.cs +++ b/NitroxClient/MonoBehaviours/Gui/MainMenu/JoinServer.cs @@ -350,7 +350,7 @@ private void StartMultiplayerClient() } catch (ClientConnectionFailedException) { - Log.InGame($"Unable to contact the remote server at: {ServerIp}:{ServerPort}"); + Log.InGameSensitive("Unable to contact the remote server at: {ip}:{port}", ServerIp, ServerPort); if (ServerIp.Equals("127.0.0.1")) { @@ -361,9 +361,8 @@ private void StartMultiplayerClient() else { Log.InGame("Seems like your firewall settings are interfering"); - } + } } - OnCancelClick(); } } @@ -420,14 +419,12 @@ private void SessionConnectionStateChangedHandler(IMultiplayerSessionConnectionS break; case MultiplayerSessionConnectionStage.AWAITING_RESERVATION_CREDENTIALS: Log.InGame("Waiting for User Input..."); - RightSideMainMenu.OpenGroup("Join Server"); FocusPlayerNameTextbox(); - break; + case MultiplayerSessionConnectionStage.SESSION_RESERVED: Log.InGame("Launching game..."); - multiplayerSession.ConnectionStateChanged -= SessionConnectionStateChangedHandler; preferencesManager.Save(); diff --git a/NitroxClient/MonoBehaviours/Gui/MainMenu/MainMenuMultiplayerPanel.cs b/NitroxClient/MonoBehaviours/Gui/MainMenu/MainMenuMultiplayerPanel.cs index 96a3d8d225..143ce8411d 100644 --- a/NitroxClient/MonoBehaviours/Gui/MainMenu/MainMenuMultiplayerPanel.cs +++ b/NitroxClient/MonoBehaviours/Gui/MainMenu/MainMenuMultiplayerPanel.cs @@ -181,6 +181,7 @@ private IPEndPoint ResolveHostName(string hostname) Match match = Regex.Match(hostname, @"^\s*([a-zA-Z\.]*)\:?(\d{2,5})?\s*$"); if (!match.Success) { + Log.ErrorSensitive("Hostname {hostname} has an invalid format", hostname); return null; } @@ -189,8 +190,9 @@ private IPEndPoint ResolveHostName(string hostname) IPHostEntry hostEntry = Dns.GetHostEntry(match.Groups[1].Value); return new IPEndPoint(hostEntry.AddressList[0], match.Groups[2].Success ? int.Parse(match.Groups[2].Value) : 11000); } - catch (SocketException) + catch (SocketException ex) { + Log.ErrorSensitive(ex, "Unable to resolve the address {hostname}", hostname); return null; } } diff --git a/NitroxClient/MonoBehaviours/Multiplayer.cs b/NitroxClient/MonoBehaviours/Multiplayer.cs index 02ffe37d2f..14c47a2228 100644 --- a/NitroxClient/MonoBehaviours/Multiplayer.cs +++ b/NitroxClient/MonoBehaviours/Multiplayer.cs @@ -77,10 +77,11 @@ public static IEnumerator LoadAsync() public void Awake() { + Log.InGameLogger = new SubnauticaInGameLogger(); Log.InGame("Multiplayer Client Loaded..."); + multiplayerSession = NitroxServiceLocator.LocateService(); packetReceiver = NitroxServiceLocator.LocateService(); - Log.InGameLogger = new SubnauticaInGameLogger(); NitroxModel.Helper.Map.Main = new SubnauticaMap(); Main = this; DontDestroyOnLoad(gameObject); @@ -111,7 +112,7 @@ public void ProcessPackets() } catch (Exception ex) { - Log.Error("Error processing packet: " + packet, ex); + Log.Error(ex, $"Error processing packet {packet}"); } } } @@ -169,7 +170,7 @@ private static void SetLoadingComplete() items.Clear(); PlayerManager remotePlayerManager = NitroxServiceLocator.LocateService(); - + LoadingScreenVersionText.DisableWarningText(); DiscordRPController.Main.InitializeInGame(Main.multiplayerSession.AuthenticationContext.Username, remotePlayerManager.GetTotalPlayerCount(), Main.multiplayerSession.IpAddress + ":" + Main.multiplayerSession.ServerPort); PlayerChatManager.LoadChatKeyHint(); diff --git a/NitroxClient/MonoBehaviours/NitroxBootstrapper.cs b/NitroxClient/MonoBehaviours/NitroxBootstrapper.cs index ea9488e0b5..3118c3f7bf 100644 --- a/NitroxClient/MonoBehaviours/NitroxBootstrapper.cs +++ b/NitroxClient/MonoBehaviours/NitroxBootstrapper.cs @@ -24,7 +24,7 @@ private void EnableDeveloperFeatures() Log.Info("Enabling developer console."); DevConsole.disableConsole = false; Application.runInBackground = true; - Log.Info($"Unity run in background set to {Application.runInBackground.ToString().ToUpperInvariant()}."); + Log.Info($"Unity run in background set to \"{Application.runInBackground}\""); } private void CreateDebugger() diff --git a/NitroxClient/MonoBehaviours/NitroxDebugManager.cs b/NitroxClient/MonoBehaviours/NitroxDebugManager.cs index 662402b270..c27fe6a600 100644 --- a/NitroxClient/MonoBehaviours/NitroxDebugManager.cs +++ b/NitroxClient/MonoBehaviours/NitroxDebugManager.cs @@ -155,17 +155,17 @@ private void OnDisable() private void SceneManager_sceneLoaded(Scene scene, LoadSceneMode loadMode) { - Log.Debug($"Scene '{scene.name}' loaded as {loadMode}"); + Log.Debug($"Scene {scene.name} loaded as {loadMode}"); } private void SceneManager_sceneUnloaded(Scene scene) { - Log.Debug($"Scene '{scene.name}' unloaded."); + Log.Debug($"Scene {scene.name} unloaded."); } private void SceneManager_activeSceneChanged(Scene fromScene, Scene toScene) { - Log.Debug($"Active scene changed from '{fromScene.name}' to '{toScene.name}'"); + Log.Debug($"Active scene changed from {fromScene.name} to {toScene.name}"); } } } diff --git a/NitroxClient/MonoBehaviours/PowerMonitor.cs b/NitroxClient/MonoBehaviours/PowerMonitor.cs index 8289297c3d..2bec8358e7 100644 --- a/NitroxClient/MonoBehaviours/PowerMonitor.cs +++ b/NitroxClient/MonoBehaviours/PowerMonitor.cs @@ -96,7 +96,7 @@ private bool CameFromActivePowerEvent() return isMethodActive; } - Log.Error("Could not find a whitelisted power method for " + method + " (from " + method.DeclaringType + ") - it might be newly introduced!"); + Log.Error($"Could not find a whitelisted power method for {method} (from {method.DeclaringType}) - it might be newly introduced!"); Log.Error(new StackTrace().ToString()); return true; diff --git a/NitroxClient/Unity/Helper/DebugUtils.cs b/NitroxClient/Unity/Helper/DebugUtils.cs index 2866453ed7..32a9bafea8 100644 --- a/NitroxClient/Unity/Helper/DebugUtils.cs +++ b/NitroxClient/Unity/Helper/DebugUtils.cs @@ -40,7 +40,7 @@ public static void PrintHierarchy(GameObject gameObject, bool startAtRoot = fals private static void TravelDown(GameObject gameObject, bool listComponents = false, string linePrefix = "", bool travelDown = true) { - Log.Debug("{0}+GameObject GUID={1} NAME={2} POSITION={3}", linePrefix, NitroxEntity.GetId(gameObject), gameObject.name, gameObject.transform.position); + Log.Debug($"{linePrefix}+GameObject GUID={NitroxEntity.GetId(gameObject)} NAME={gameObject.name} POSITION={gameObject.transform.position}"); if (listComponents) { ListComponents(gameObject, linePrefix); @@ -61,7 +61,7 @@ private static void ListComponents(GameObject gameObject, string linePrefix = "" Component[] allComponents = gameObject.GetComponents(); foreach (Component c in allComponents) { - Log.Debug("{0} =Component NAME={1}", linePrefix, c.GetType().Name); + Log.Debug($"{linePrefix}=Component NAME={c.GetType().Name}"); } } } diff --git a/NitroxLauncher/App.xaml.cs b/NitroxLauncher/App.xaml.cs index 715da5bcfd..00ac1d6007 100644 --- a/NitroxLauncher/App.xaml.cs +++ b/NitroxLauncher/App.xaml.cs @@ -11,6 +11,8 @@ public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { + Log.Setup(); + // Set default style for all windows to the style with the target type 'Window' (in App.xaml). FrameworkElement.StyleProperty.OverrideMetadata(typeof(Window), new FrameworkPropertyMetadata @@ -50,8 +52,7 @@ private void Application_DispatcherUnhandledException(object sender, DispatcherU // If something went wrong. Close the server MainWindow window = (MainWindow)Current.MainWindow; window?.CloseInternalServerAndRemovePatchAsync(); - - Log.Error(e.Exception.GetBaseException().ToString()); + Log.Error(e.Exception.GetBaseException().ToString()); // Gets the exception that was unhandled, not the "dispatched unhandled" exception. MessageBox.Show(GetExceptionError(e.Exception), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } diff --git a/NitroxModel-Subnautica/Logger/SubnauticaInGameLogger.cs b/NitroxModel-Subnautica/Logger/SubnauticaInGameLogger.cs index 891b22817a..b1d93e9357 100644 --- a/NitroxModel-Subnautica/Logger/SubnauticaInGameLogger.cs +++ b/NitroxModel-Subnautica/Logger/SubnauticaInGameLogger.cs @@ -4,9 +4,14 @@ namespace NitroxModel_Subnautica.Logger { public class SubnauticaInGameLogger : InGameLogger { - public void Log(string text) + public void Log(object message) => Log(message?.ToString()); + public void Log(string message) { - ErrorMessage.AddMessage(text); + if (string.IsNullOrEmpty(message)) + { + return; + } + ErrorMessage.AddMessage(message); } } } diff --git a/NitroxModel/Logger/InGameLogger.cs b/NitroxModel/Logger/InGameLogger.cs index e918278871..5a77f60f78 100644 --- a/NitroxModel/Logger/InGameLogger.cs +++ b/NitroxModel/Logger/InGameLogger.cs @@ -2,6 +2,7 @@ { public interface InGameLogger { - void Log(string text); + void Log(object message); + void Log(string message); } } diff --git a/NitroxModel/Logger/Log.cs b/NitroxModel/Logger/Log.cs index 3668184b21..7d24b96f50 100644 --- a/NitroxModel/Logger/Log.cs +++ b/NitroxModel/Logger/Log.cs @@ -1,103 +1,208 @@ using System; -using System.IO; +using System.Collections.Generic; +using System.Diagnostics; using System.Reflection; -using log4net; -using log4net.Appender; -using log4net.Core; -using log4net.Filter; -using log4net.Layout; -using log4net.Repository.Hierarchy; -using NitroxModel.Discovery; +using NLog; +using NLog.Conditions; +using NLog.Config; +using NLog.Filters; +using NLog.Fluent; +using NLog.MessageTemplates; +using NLog.Targets; +using NLog.Targets.Wrappers; +using NLog.Time; namespace NitroxModel.Logger { - public class Log + public static class Log { - private static bool inGameMessages; + /// + /// Parameters that are being logged with these names should be excluded when a log was made through the sensitive + /// method calls. + /// + private static readonly HashSet sensitiveLogParameters = new HashSet + { + "username", + "password", + "ip", + "hostname" + }; - private static readonly ILog log = LogManager.GetLogger(GetLoggerName()); - public static InGameLogger InGameLogger { get; set; } + private static NLog.Logger logger; - static Log() - { - Setup(); - } + public static InGameLogger InGameLogger { private get; set; } - // Enable the in-game notifications - public static void EnableInGameMessages() + public static void Setup(bool performanceCritical = false) { - inGameMessages = true; - } + if (logger != null) + { + throw new Exception($"{nameof(Log)} setup should only be executed once."); + } + logger = LogManager.GetCurrentClassLogger(); - // For in-game notifications - public static void InGame(string msg) - { - if (inGameMessages) + LoggingConfiguration config = new LoggingConfiguration(); + string layout = $@"[${{date:format=HH\:mm\:ss}} {GetLoggerName()}${{event-properties:item={nameof(PlayerName)}}}][${{level:uppercase=true}}] ${{message}} ${{exception}}"; + + // Targets where to log to: File and Console + ColoredConsoleTarget logConsole = new ColoredConsoleTarget(nameof(logConsole)) { - InGameLogger?.Log(msg); - Info(msg); + Layout = layout, + DetectConsoleAvailable = true + }; + + logConsole.RowHighlightingRules.Add(new ConsoleRowHighlightingRule + { + Condition = ConditionParser.ParseExpression("level == LogLevel.Error"), + ForegroundColor = ConsoleOutputColor.Red + }); + logConsole.RowHighlightingRules.Add(new ConsoleRowHighlightingRule + { + Condition = ConditionParser.ParseExpression("level == LogLevel.Warn"), + ForegroundColor = ConsoleOutputColor.Yellow + }); + logConsole.RowHighlightingRules.Add(new ConsoleRowHighlightingRule + { + Condition = ConditionParser.ParseExpression("level == LogLevel.Debug"), + ForegroundColor = ConsoleOutputColor.DarkGray + }); + + FileTarget logFile = new FileTarget(nameof(logFile)) + { + FileName = $"Nitrox Logs/Nitrox-{GetLoggerName()}.log", + ArchiveFileName = "Nitrox Logs/archives/Nitrox-{GetLoggerName()}.{#}.log", + ArchiveEvery = FileArchivePeriod.Day, + ArchiveNumbering = ArchiveNumberingMode.Date, + MaxArchiveFiles = 7, + Layout = layout, + EnableArchiveFileCompression = true, + }; + AsyncTargetWrapper logFileAsync = new AsyncTargetWrapper(logFile, 1000, AsyncTargetWrapperOverflowAction.Grow); + + // Rules for mapping loggers to targets + config.AddRule(LogLevel.Debug, LogLevel.Fatal, logConsole); + config.AddRule(LogLevel.Debug, LogLevel.Fatal, logFileAsync); + config.AddRuleForOneLevel(LogLevel.Info, + new MethodCallTarget("ingame", + (evt, obj) => + { + if (InGameLogger == null) + { + return; + } + evt.Properties.TryGetValue("game", out object isGameLog); + if (isGameLog != null && (bool)isGameLog) + { + InGameLogger.Log(evt.FormattedMessage); + } + })); + + AddSensitiveFilter(config, target => target is AsyncTargetWrapper || target is FileTarget); + + // Apply config + LogManager.Configuration = config; + if (!performanceCritical) + { + TimeSource.Current = new AccurateLocalTimeSource(); } } - public static void Error(string msg) + public static string PlayerName { - log.Error(msg); + set + { +#if DEBUG //Player name in log file is just important with two instances => Developer + if (string.IsNullOrEmpty(value)) + { + return; + } + + logger.Info($"Setting player name to {value}"); + logger.SetProperty(nameof(PlayerName), $"-{value}"); +#endif + } } - public static void Error(string fmt, params object[] arg) - { - log.Error(Format(fmt, arg)); - } + [Conditional("DEBUG")] + public static void Debug(string message) => logger.Debug(message); + [Conditional("DEBUG")] + public static void Debug(object message) => Debug(message?.ToString()); - public static void Error(string msg, Exception ex) - { - log.Error(msg, ex); - } + public static void Info(string message) => logger.Info(message); + public static void Info(object message) => Info(message?.ToString()); + + public static void Warn(string message) => logger.Warn(message); + public static void Warn(object message) => Warn(message?.ToString()); + + public static void Error(Exception ex) => logger.Error(ex); + public static void Error(Exception ex, string message) => logger.Error(ex, message); + public static void Error(string message) => logger.Error(message); - public static void Warn(string msg) + public static void InGame(object message) => InGame(message?.ToString()); + public static void InGame(string message) { - log.Warn(msg); + if (InGameLogger == null) + { + logger.Warn($"{nameof(InGameLogger)} has not been set."); + return; + } + logger + .WithProperty("game", true) + .Info() + .Message(message) + .Write(); } - public static void Warn(string fmt, params object[] arg) + [Conditional("DEBUG")] + public static void DebugSensitive(string message, params object[] args) { - log.Warn(Format(fmt, arg)); + logger + .WithProperty("sensitive", true) + .Debug() + .Message(message, args) + .Write(); } - public static void Info(string msg) + public static void InfoSensitive(string message, params object[] args) { - log.Info(msg); + logger + .WithProperty("sensitive", true) + .Info() + .Message(message, args) + .Write(); } - public static void Info(string fmt, params object[] arg) + public static void ErrorSensitive(Exception ex, string message, params object[] args) { - log.Info(Format(fmt, arg)); + logger + .WithProperty("sensitive", true) + .Error() + .Exception(ex) + .Message(message, args) + .Write(); } - public static void Info(object o) + public static void ErrorSensitive(string message, params object[] args) { - string msg = o == null ? "null" : o.ToString(); - Info(msg); + logger + .WithProperty("sensitive", true) + .Error() + .Message(message, args) + .Write(); } - // Only for debug prints. Should not be displayed to general user. - // Should we print the calling method for this for more debug context? - public static void Debug(string fmt, params object[] arg) + public static void InGameSensitive(string message, params object[] args) { - if (arg == null || arg.Length < 1) + if (InGameLogger == null) { - log.Debug(fmt); + logger.Warn($"{nameof(InGameLogger)} has not been set."); + return; } - else - { - log.Debug(Format(fmt, arg)); - } - } - - public static void Debug(object o) - { - string msg = o == null ? "null" : o.ToString(); - Debug(msg); + logger + .WithProperty("sensitive", true) + .WithProperty("game", true) + .Info() + .Message(message, args) + .Write(); } /// @@ -110,46 +215,40 @@ private static string GetLoggerName() return name.IndexOf("server", StringComparison.InvariantCultureIgnoreCase) >= 0 ? "Server" : name; } - // Helping method for formatting string correctly with arguments - private static string Format(string fmt, params object[] arg) - { - return string.Format(fmt, arg); - } - - private static void Setup() + /// + /// Exclude sensitive logs parameters from being logged into (long-term) files + /// + /// The logger config to apply the filter to. + /// Custom condition to decide whether to apply the sensitive log file to a log target. + private static void AddSensitiveFilter(LoggingConfiguration config, Func applyDecider) { - Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(); - - PatternLayout patternLayout = new PatternLayout(); - patternLayout.ConversionPattern = "[%d{HH:mm:ss} %logger %level]: %m%n"; - patternLayout.ActivateOptions(); - - LevelRangeFilter filter = new LevelRangeFilter(); - filter.LevelMin = Level.Debug; - filter.LevelMax = Level.Fatal; - - RollingFileAppender fileAppender = new RollingFileAppender(); - string basePath = GameInstallationFinder.Instance.FindGame(); - fileAppender.File = Path.Combine(basePath ?? "", "Nitrox Logs", "nitrox-.log"); // Attempt to create 'Nitrox Logs' dir where the game is. - fileAppender.AppendToFile = true; - fileAppender.RollingStyle = RollingFileAppender.RollingMode.Date; - fileAppender.MaxSizeRollBackups = 10; - fileAppender.DatePattern = "yyyy-MM-dd"; - fileAppender.StaticLogFileName = false; - fileAppender.PreserveLogFileNameExtension = true; - fileAppender.LockingModel = new FileAppender.MinimalLock(); - fileAppender.Layout = patternLayout; - fileAppender.ActivateOptions(); - fileAppender.AddFilter(filter); - - ConsoleAppender consoleAppender = new ConsoleAppender(); - consoleAppender.Layout = patternLayout; - consoleAppender.AddFilter(filter); - - hierarchy.Root.AddAppender(consoleAppender); - hierarchy.Root.AddAppender(fileAppender); - - hierarchy.Configured = true; + WhenMethodFilter sensitiveLogFilter = new WhenMethodFilter(context => + { + context.Properties.TryGetValue("sensitive", out object isSensitive); + if (isSensitive != null && (bool)isSensitive) + { + for (int i = 0; i < context.MessageTemplateParameters.Count; i++) + { + MessageTemplateParameter template = context.MessageTemplateParameters[i]; + if (sensitiveLogParameters.Contains(template.Name)) + { + context.Parameters.SetValue(new string('*', template.Value?.ToString().Length ?? 0), i); + } + } + context.Parameters = context.Parameters; // Triggers NLog to format the message again + } + return FilterResult.Log; + }); + foreach (LoggingRule rule in config.LoggingRules) + { + foreach (Target target in rule.Targets) + { + if (applyDecider(target)) + { + rule.Filters.Add(sensitiveLogFilter); + } + } + } } } } diff --git a/NitroxModel/NitroxModel.csproj b/NitroxModel/NitroxModel.csproj index c020493023..ccadbad33e 100644 --- a/NitroxModel/NitroxModel.csproj +++ b/NitroxModel/NitroxModel.csproj @@ -32,22 +32,23 @@ ..\packages\Autofac.2.6.3.862\lib\NET35\Autofac.Configuration.dll - - ..\packages\log4net.2.0.8\lib\net35-full\log4net.dll - ..\Nitrox.Subnautica.Assets\LZ4.dll + + + ..\packages\NLog.4.7.2\lib\net40-client\NLog.dll + ..\Nitrox.Subnautica.Assets\protobuf-net.dll - + - - + + @@ -104,6 +105,7 @@ + @@ -135,7 +137,6 @@ - @@ -225,4 +226,4 @@ - + \ No newline at end of file diff --git a/NitroxModel/Packets/Packet.cs b/NitroxModel/Packets/Packet.cs index e9d3e0a28a..44fea334ba 100644 --- a/NitroxModel/Packets/Packet.cs +++ b/NitroxModel/Packets/Packet.cs @@ -17,19 +17,22 @@ public abstract class Packet private static readonly SurrogateSelector surrogateSelector; private static readonly StreamingContext streamingContext; private static readonly BinaryFormatter serializer; - + + private static readonly string[] blacklistedAssemblies = { "NLog" }; + static Packet() { surrogateSelector = new SurrogateSelector(); streamingContext = new StreamingContext(StreamingContextStates.All); // Our surrogates can be safely used in every context. IEnumerable types = AppDomain.CurrentDomain.GetAssemblies() - .SelectMany(a => a.GetTypes() - .Where(t => - t.BaseType != null && - t.BaseType.IsGenericType && - t.BaseType.GetGenericTypeDefinition() == typeof(SerializationSurrogate<>) && - t.IsClass && - !t.IsAbstract)); + .Where(assembly => !blacklistedAssemblies.Contains(assembly.GetName().Name)) + .SelectMany(a => a.GetTypes() + .Where(t => + t.BaseType != null && + t.BaseType.IsGenericType && + t.BaseType.GetGenericTypeDefinition() == typeof(SerializationSurrogate<>) && + t.IsClass && + !t.IsAbstract)); foreach (Type type in types) { @@ -37,7 +40,7 @@ static Packet() Type surrogatedType = type.BaseType.GetGenericArguments()[0]; surrogateSelector.AddSurrogate(surrogatedType, streamingContext, surrogate); - Log.Debug("Added surrogate " + surrogate.GetType().Name + " for type " + surrogatedType); + Log.Debug($"Added surrogate {surrogate.GetType().Name} for type {surrogatedType}"); } // For completeness, we could pass a StreamingContextStates.CrossComputer. @@ -87,7 +90,7 @@ public static bool IsTypeSerializable(Type type) ISurrogateSelector selector; return (serializer.SurrogateSelector.GetSurrogate(type, Packet.serializer.Context, out selector) != null); } - + public WrapperPacket ToWrapperPacket() { return new WrapperPacket(Serialize()); diff --git a/NitroxModel/Server/ServerConfigItem.cs b/NitroxModel/Server/ServerConfigItem.cs index 030a62ff8f..e2a346bc99 100644 --- a/NitroxModel/Server/ServerConfigItem.cs +++ b/NitroxModel/Server/ServerConfigItem.cs @@ -32,7 +32,7 @@ public T Value } catch (Exception ex) { - Log.Error("Can't refresh server app settings", ex); + Log.Error(ex, "Can't refresh server app settings"); } } @@ -44,7 +44,7 @@ public ServerConfigItem(string itemName, T defaultValue) Name = itemName; value = defaultValue; //not Value, we don't want to rewrite the config to default value again and again - + try { TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); diff --git a/NitroxModel/packages.config b/NitroxModel/packages.config index fbdd460dc1..3485b9c887 100644 --- a/NitroxModel/packages.config +++ b/NitroxModel/packages.config @@ -1,5 +1,5 @@  - + \ No newline at end of file diff --git a/NitroxPatcher/Main.cs b/NitroxPatcher/Main.cs index 396022773a..ca29f4a310 100644 --- a/NitroxPatcher/Main.cs +++ b/NitroxPatcher/Main.cs @@ -26,16 +26,16 @@ public static class Main public static void Execute() { - Log.EnableInGameMessages(); + Log.Setup(true); Optional.ApplyHasValueCondition(o => (bool)o); if (container != null) { - Log.Warn("Patches have already been detected! Call Apply or Restore instead."); + Log.Warn($"Patches have already been detected! Call {nameof(Apply)} or {nameof(Restore)} instead."); return; } - Log.Info("Registering Dependencies"); + Log.Info("Registering dependencies"); container = CreatePatchingContainer(); NitroxServiceLocator.InitializeDependencyContainer(new ClientAutoFacRegistrar()); @@ -53,7 +53,7 @@ public static void Apply() foreach (IDynamicPatch patch in container.Resolve()) { - Log.Info("Applying dynamic patch " + patch.GetType().Name); + Log.Debug($"Applying dynamic patch {patch.GetType().Name}"); patch.Patch(harmony); } @@ -74,7 +74,7 @@ public static void Restore() foreach (IDynamicPatch patch in container.Resolve()) { - Log.Info("Restoring dynamic patch " + patch.GetType().Name); + Log.Debug($"Restoring dynamic patch {patch.GetType().Name}"); patch.Restore(harmony); } @@ -90,13 +90,13 @@ private static void InitPatches() foreach (IPersistentPatch patch in container.Resolve>()) { - Log.Info("Applying persistent patch " + patch.GetType().Name); + Log.Debug($"Applying persistent patch {patch.GetType().Name}"); patch.Patch(harmony); } Multiplayer.OnBeforeMultiplayerStart += Apply; Multiplayer.OnAfterMultiplayerEnd += Restore; - Log.Info("Completed patching using " + Assembly.GetExecutingAssembly().FullName); + Log.Info($"Completed patching using {Assembly.GetExecutingAssembly().FullName}"); } private static IContainer CreatePatchingContainer() diff --git a/NitroxServer-Subnautica/Program.cs b/NitroxServer-Subnautica/Program.cs index 4c0221b767..93ff8531dd 100644 --- a/NitroxServer-Subnautica/Program.cs +++ b/NitroxServer-Subnautica/Program.cs @@ -44,6 +44,7 @@ private static void Main(string[] args) AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomainOnAssemblyResolve; ConfigureConsoleWindow(); ConfigureCultureInfo(); + Log.Setup(); NitroxModel.Helper.Map.Main = new SubnauticaMap(); @@ -62,9 +63,9 @@ private static void Main(string[] args) Console.ReadKey(true); } } - catch (Exception e) + catch (Exception ex) { - Log.Error(e.ToString()); + Log.Error(ex); return; } @@ -159,7 +160,7 @@ private static void CatchExitEvent() // Prevents Garbage Collection issue where server closes and an exception occurs for this handle. private static readonly ConsoleEventDelegate consoleCtrlCheckDelegate = ConsoleEventCallback; - + private static bool ConsoleEventCallback(int eventType) { if (eventType == 2) // close diff --git a/NitroxServer/Communication/Packets/PacketHandler.cs b/NitroxServer/Communication/Packets/PacketHandler.cs index 2a3750abe6..9297759248 100644 --- a/NitroxServer/Communication/Packets/PacketHandler.cs +++ b/NitroxServer/Communication/Packets/PacketHandler.cs @@ -67,8 +67,7 @@ private void ProcessUnauthenticated(Packet packet, NitroxConnection connection) } catch (Exception ex) { - Log.Info("Received invalid, unauthenticated packet: " + packet); - Log.Error("Exception:", ex); + Log.Error(ex, $"Received invalid, unauthenticated packet: {packet}"); } } } diff --git a/NitroxServer/Communication/Packets/Processors/SubRootChangedPacketProcessor.cs b/NitroxServer/Communication/Packets/Processors/SubRootChangedPacketProcessor.cs index 725c96aabc..cb34dba6ab 100644 --- a/NitroxServer/Communication/Packets/Processors/SubRootChangedPacketProcessor.cs +++ b/NitroxServer/Communication/Packets/Processors/SubRootChangedPacketProcessor.cs @@ -16,7 +16,7 @@ public SubRootChangedPacketProcessor(PlayerManager playerManager) public override void Process(SubRootChanged packet, Player player) { - Log.Info(packet); + Log.Debug(packet); player.SubRootId = packet.SubRootId; playerManager.SendPacketToOtherPlayers(packet, player); } diff --git a/NitroxServer/Communication/Packets/Processors/VehicleAddPacketProcessor.cs b/NitroxServer/Communication/Packets/Processors/VehicleAddPacketProcessor.cs index 6cab26da2b..64e0c2b33b 100644 --- a/NitroxServer/Communication/Packets/Processors/VehicleAddPacketProcessor.cs +++ b/NitroxServer/Communication/Packets/Processors/VehicleAddPacketProcessor.cs @@ -19,7 +19,7 @@ public VehicleAddPacketProcessor(PlayerManager playerManager, VehicleManager veh public override void Process(VehicleCreated packet, Player player) { - Log.Info(packet); + Log.Debug(packet); vehicleManager.AddVehicle(packet.CreatedVehicle); playerManager.SendPacketToOtherPlayers(packet, player); } diff --git a/NitroxServer/Communication/Packets/Processors/VehicleColorChangeProcessor.cs b/NitroxServer/Communication/Packets/Processors/VehicleColorChangeProcessor.cs index a9f952968c..3b3b891fb8 100644 --- a/NitroxServer/Communication/Packets/Processors/VehicleColorChangeProcessor.cs +++ b/NitroxServer/Communication/Packets/Processors/VehicleColorChangeProcessor.cs @@ -22,7 +22,7 @@ public override void Process(VehicleColorChange packet, Player player) vehicleManager.UpdateVehicleColours(packet.Index, packet.Id, packet.HSB); playerManager.SendPacketToOtherPlayers(packet, player); - Log.Info(packet); + Log.Debug("Received packet: " + packet); } } } diff --git a/NitroxServer/Communication/Packets/Processors/VehicleDockingProcessor.cs b/NitroxServer/Communication/Packets/Processors/VehicleDockingProcessor.cs index 363def737a..599b864b4c 100644 --- a/NitroxServer/Communication/Packets/Processors/VehicleDockingProcessor.cs +++ b/NitroxServer/Communication/Packets/Processors/VehicleDockingProcessor.cs @@ -25,7 +25,7 @@ public override void Process(VehicleDocking packet, Player player) if (!vehicle.HasValue) { - Log.Error("VehicleDocking received for vehicle id {0} that does not exist!", packet.VehicleId); + Log.Error($"VehicleDocking received for vehicle id {packet.VehicleId} that does not exist!"); return; } diff --git a/NitroxServer/ConsoleCommands/Abstract/Command.cs b/NitroxServer/ConsoleCommands/Abstract/Command.cs index e64f742927..30a7ddfd7d 100644 --- a/NitroxServer/ConsoleCommands/Abstract/Command.cs +++ b/NitroxServer/ConsoleCommands/Abstract/Command.cs @@ -57,13 +57,13 @@ public void TryExecute(Optional sender, string[] args) { Execute(new CallArgs(this, sender, args)); } - catch (ArgumentException e) + catch (ArgumentException ex) { - SendMessage(sender, $"Error: {e.Message}"); + SendMessage(sender, $"Error: {ex.Message}"); } - catch (Exception e) + catch (Exception ex) { - Log.Error("Fatal error while trying to execute the command", e); + Log.Error(ex, "Fatal error while trying to execute the command"); } } diff --git a/NitroxServer/ConsoleCommands/ChangeAdminPasswordCommand.cs b/NitroxServer/ConsoleCommands/ChangeAdminPasswordCommand.cs index 2fafa5d975..0b88c7610b 100644 --- a/NitroxServer/ConsoleCommands/ChangeAdminPasswordCommand.cs +++ b/NitroxServer/ConsoleCommands/ChangeAdminPasswordCommand.cs @@ -22,7 +22,7 @@ protected override void Execute(CallArgs args) serverConfig.AdminPassword = newPassword; - Log.Info($"Admin password changed to \"{newPassword}\" by {args.SenderName}"); + Log.InfoSensitive("Admin password changed to {password} by {playername}", newPassword, args.SenderName); SendMessageToPlayer(args.Sender, "Admin password changed"); } } diff --git a/NitroxServer/ConsoleCommands/ChangeServerPasswordCommand.cs b/NitroxServer/ConsoleCommands/ChangeServerPasswordCommand.cs index 0abcedad5c..03bdc70fdc 100644 --- a/NitroxServer/ConsoleCommands/ChangeServerPasswordCommand.cs +++ b/NitroxServer/ConsoleCommands/ChangeServerPasswordCommand.cs @@ -22,7 +22,7 @@ protected override void Execute(CallArgs args) serverConfig.ServerPassword = password; - Log.Info($"Server password changed to \"{password}\" by {args.SenderName}"); + Log.InfoSensitive("Server password changed to {password} by {playername}", password, args.SenderName); SendMessageToPlayer(args.Sender, "Server password changed"); } } diff --git a/NitroxServer/GameLogic/Items/InventoryManager.cs b/NitroxServer/GameLogic/Items/InventoryManager.cs index edcdbad8d8..5ad322d913 100644 --- a/NitroxServer/GameLogic/Items/InventoryManager.cs +++ b/NitroxServer/GameLogic/Items/InventoryManager.cs @@ -20,7 +20,7 @@ public InventoryManager(List inventoryItems, List storageSlo public void ItemAdded(ItemData itemData) { inventoryItemsById[itemData.ItemId] = itemData; - Log.Debug($"Received inventory item '{itemData.ItemId}' to container '{itemData.ContainerId}'. Total items: {inventoryItemsById.Count}"); + Log.Debug($"Received inventory item {itemData.ItemId} to container {itemData.ContainerId}. Total items: {inventoryItemsById.Count}"); } public void ItemRemoved(NitroxId itemId) diff --git a/NitroxServer/GameLogic/TimeKeeper.cs b/NitroxServer/GameLogic/TimeKeeper.cs index e764daa4ce..cc502d8fcb 100644 --- a/NitroxServer/GameLogic/TimeKeeper.cs +++ b/NitroxServer/GameLogic/TimeKeeper.cs @@ -18,7 +18,7 @@ public class TimeKeeper // Discrepancy value for player based time modifications private float correctionValue; - public DateTime ServerStartTime { get; set; } = DateTime.Now; + public DateTime ServerStartTime { get; set; } = DateTime.UtcNow; public void SetDay() { @@ -56,7 +56,7 @@ private float CurrentTime { get { - TimeSpan interval = DateTime.Now - ServerStartTime; + TimeSpan interval = DateTime.UtcNow - ServerStartTime; return SUBNAUTICA_BEGIN_TIME_OFFSET + Convert.ToSingle(interval.TotalSeconds) + correctionValue; } } diff --git a/NitroxServer/IpLogger.cs b/NitroxServer/IpLogger.cs index 225aec9e4d..41f142de3d 100644 --- a/NitroxServer/IpLogger.cs +++ b/NitroxServer/IpLogger.cs @@ -41,7 +41,7 @@ private static void PrintIfHamachi(NetworkInterface netInterface) IEnumerable ips = netInterface.GetIPProperties().UnicastAddresses .Select(address => address.Address.ToString()) .Where(address => !address.ToString().Contains("fe80::")); - Log.Info("If using Hamachi, use this IP: " + string.Join(" or ", ips)); + Log.InfoSensitive("If using Hamachi, use this IP: {ip}", string.Join(" or ", ips)); } private static void PrintIfLan(NetworkInterface netInterface) @@ -62,7 +62,7 @@ private static void PrintIfLan(NetworkInterface netInterface) if (splitIpParts[0] == "10" || splitIpParts[0] == "192" && splitIpParts[1] == "168" || splitIpParts[0] == "172" && secondPart > 15 && secondPart < 32) //To get if IP is private { - Log.Info("If playing on LAN, use this IP: " + eachIp.Address); + Log.Info($"If playing on LAN, use this IP: {eachIp.Address}"); // Local IP doesn't need sensitive logging } } } @@ -94,12 +94,12 @@ private static void ExternalIpStringDownloadCompleted(object sender, DownloadStr { if (!e.Cancelled && e.Error == null) { - Log.Info($"If using port forwarding, use this IP: {e.Result}"); + Log.InfoSensitive("If using port forwarding, use this IP: {ip}", e.Result); } else { Log.Warn("Could not get your external IP. You are on your own..."); - } + } } } } diff --git a/NitroxServer/NitroxServer.csproj b/NitroxServer/NitroxServer.csproj index 87a9e04d79..c5843a8305 100644 --- a/NitroxServer/NitroxServer.csproj +++ b/NitroxServer/NitroxServer.csproj @@ -72,7 +72,7 @@ - + diff --git a/NitroxServer/Serialization/BatchCellsParser.cs b/NitroxServer/Serialization/BatchCellsParser.cs index 376235ea98..30fef3fc31 100644 --- a/NitroxServer/Serialization/BatchCellsParser.cs +++ b/NitroxServer/Serialization/BatchCellsParser.cs @@ -62,7 +62,6 @@ public void ParseFile(Int3 batchId, string pathPrefix, string prefix, string suf if (!File.Exists(fileName)) { - //Log.Debug("File does not exist: " + fileName); return; } diff --git a/NitroxServer/Serialization/ServerJsonSerializer.cs b/NitroxServer/Serialization/ServerJsonSerializer.cs index 91f3edd3d9..375ec0a277 100644 --- a/NitroxServer/Serialization/ServerJsonSerializer.cs +++ b/NitroxServer/Serialization/ServerJsonSerializer.cs @@ -19,7 +19,7 @@ public ServerJsonSerializer() serializer.Error += delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs e) { - Log.Error("Error in JsonSerializer.", e.ErrorContext.Error); + Log.Error(e.ErrorContext.Error, "Error while initializing JsonSerializer."); }; RegisterConverters(); diff --git a/NitroxServer/Serialization/ServerProtoBufSerializer.cs b/NitroxServer/Serialization/ServerProtoBufSerializer.cs index f8643e2043..289aa348eb 100644 --- a/NitroxServer/Serialization/ServerProtoBufSerializer.cs +++ b/NitroxServer/Serialization/ServerProtoBufSerializer.cs @@ -81,7 +81,7 @@ private void RegisterAssemblyClasses(string assemblyName) } else { - Log.Error($"ServerProtoBufSerializer has thrown an error registering the type: {type} from {assemblyName}", ex); + Log.Error(ex, $"ServerProtoBufSerializer has thrown an error registering the type: {type} from {assemblyName}"); } } } diff --git a/NitroxServer/Serialization/World/WorldPersistence.cs b/NitroxServer/Serialization/World/WorldPersistence.cs index 97cb59cae6..fa2584bd12 100644 --- a/NitroxServer/Serialization/World/WorldPersistence.cs +++ b/NitroxServer/Serialization/World/WorldPersistence.cs @@ -230,8 +230,8 @@ private World CreateWorld(DateTime serverStartTime, world.EntitySimulation = new EntitySimulation(world.EntityManager, world.SimulationOwnershipData, world.PlayerManager, serverSpawnedSimulationWhiteList); Log.Info($"World GameMode: {gameMode}"); - Log.Info($"Server Password: {(string.IsNullOrEmpty(config.ServerPassword) ? "None. Public Server." : config.ServerPassword)}"); - Log.Info($"Admin Password: {config.AdminPassword}"); + Log.InfoSensitive("Server Password: {password}", string.IsNullOrEmpty(config.ServerPassword) ? "None. Public Server." : config.ServerPassword); + Log.InfoSensitive("Admin Password: {password}", config.AdminPassword); Log.Info($"Autosave: {(config.DisableAutoSave ? "DISABLED" : $"ENABLED ({config.SaveInterval / 60000} min)")}"); Log.Info("To get help for commands, run help in console or /help in chatbox");