Skip to content

Commit

Permalink
Use Nlog logging
Browse files Browse the repository at this point in the history
* SubnauticaNitrox#913 Added NLog and supporting instance class

* SubnauticaNitrox#913 shifted classes and added async calling on logging file

* SubnauticaNitrox#913 added all interface methods and implemetations for logger

* SubnauticaNitrox#913 added config file for NLog with formatting

* SubnauticaNitrox#913 Removed old log error method and replaced it with new one

* SubnauticaNitrox#913 changed warnings, trace and error

* SubnauticaNitrox#913 updated all the debug instances

* SubnauticaNitrox#913 removed old logger class

* SubnauticaNitrox#913 Renamed log class and removed log4net

* SubnauticaNitrox#913 quick changes after reviewing my own pull request and reading the submission guidelines

* SubnauticaNitrox#913 Updated some thing to actually match the acceptance of the ticket 🤦

* SubnauticaNitrox#913 Changed log back to static class and split out methods

* SubnauticaNitrox#913 PR changes to move the nlog config to a more global place and removed the enum for catogorey

* SubnauticaNitrox#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
  • Loading branch information
Jannify authored May 29, 2020
1 parent 5ffc5d0 commit 92e6549
Show file tree
Hide file tree
Showing 42 changed files with 323 additions and 209 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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)
{
Expand Down Expand Up @@ -80,7 +80,7 @@ private IEnumerator RunPendingProcessors()
}
}
}

private bool HasDependenciesSatisfied(InitialSyncProcessor processor)
{
foreach (Type dependentType in processor.DependentProcessors)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Pickupable>();

if (pickupable != null && itemdata.ContainerId == packet.PlayerGameObjectId)
Expand All @@ -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");
}
}
}
14 changes: 7 additions & 7 deletions NitroxClient/GameLogic/InitialSync/PdaInitialSyncProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ public override IEnumerator Process(InitialPlayerSync packet, WaitScreen.ManualW
waitScreenItem.SetProgress(1f);
yield return null;
}

private void SetEncyclopediaEntry(List<string> 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<PDAEncyclopediaEntryAdd>())
{
Expand All @@ -66,7 +66,7 @@ private void SetPDAEntryComplete(List<NitroxTechType> 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}");

}

Expand All @@ -79,12 +79,12 @@ private void SetPDAEntryPartial(List<PDAEntry> 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<NitroxTechType> 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<KnownTechEntryAdd>())
{
Expand All @@ -98,7 +98,7 @@ private void SetKnownTech(List<NitroxTechType> techTypes)

private void SetPDALog(List<PDALogEntry> 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<PDALogEntryAdd>())
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ public override IEnumerator Process(InitialPlayerSync packet, WaitScreen.ManualW
int storageSlotsSynced = 0;

using (packetSender.Suppress<StorageSlotItemAdd>())
{
{
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);
Expand Down
14 changes: 7 additions & 7 deletions NitroxClient/GameLogic/ItemContainers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()}");
}
}

Expand All @@ -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()}");
}
}

Expand All @@ -48,13 +48,13 @@ public void AddItem(GameObject item, NitroxId containerId)
Optional<GameObject> 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<ItemsContainer> 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;
}

Expand All @@ -73,7 +73,7 @@ public void RemoveItem(NitroxId ownerId, NitroxId itemId)
Optional<ItemsContainer> 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;
}

Expand All @@ -96,9 +96,9 @@ public NitroxId GetCyclopsLockerId(Transform ownerTransform)
StorageContainer storageContainer = locker.GetComponentInChildren<StorageContainer>();
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);
}

Expand Down
2 changes: 1 addition & 1 deletion NitroxClient/GameLogic/NitroxConsole.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}

Expand Down
4 changes: 2 additions & 2 deletions NitroxClient/GameLogic/Spawning/SerializedEntitySpawner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public bool SpawnsOwnChildren()
{
return false;
}

private void EnableRigidBody(GameObject gameObject)
{
Rigidbody rigidBody = gameObject.RequireComponent<Rigidbody>();
Expand All @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions NitroxClient/GameLogic/Vehicles.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
}
}

Expand Down Expand Up @@ -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}");
}
}

Expand Down
9 changes: 3 additions & 6 deletions NitroxClient/MonoBehaviours/Gui/MainMenu/JoinServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
{
Expand All @@ -361,9 +361,8 @@ private void StartMultiplayerClient()
else
{
Log.InGame("Seems like your firewall settings are interfering");
}
}
}

OnCancelClick();
}
}
Expand Down Expand Up @@ -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();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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;
}
}
Expand Down
7 changes: 4 additions & 3 deletions NitroxClient/MonoBehaviours/Multiplayer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,11 @@ public static IEnumerator LoadAsync()

public void Awake()
{
Log.InGameLogger = new SubnauticaInGameLogger();
Log.InGame("Multiplayer Client Loaded...");

multiplayerSession = NitroxServiceLocator.LocateService<IMultiplayerSession>();
packetReceiver = NitroxServiceLocator.LocateService<PacketReceiver>();
Log.InGameLogger = new SubnauticaInGameLogger();
NitroxModel.Helper.Map.Main = new SubnauticaMap();
Main = this;
DontDestroyOnLoad(gameObject);
Expand Down Expand Up @@ -111,7 +112,7 @@ public void ProcessPackets()
}
catch (Exception ex)
{
Log.Error("Error processing packet: " + packet, ex);
Log.Error(ex, $"Error processing packet {packet}");
}
}
}
Expand Down Expand Up @@ -169,7 +170,7 @@ private static void SetLoadingComplete()
items.Clear();

PlayerManager remotePlayerManager = NitroxServiceLocator.LocateService<PlayerManager>();

LoadingScreenVersionText.DisableWarningText();
DiscordRPController.Main.InitializeInGame(Main.multiplayerSession.AuthenticationContext.Username, remotePlayerManager.GetTotalPlayerCount(), Main.multiplayerSession.IpAddress + ":" + Main.multiplayerSession.ServerPort);
PlayerChatManager.LoadChatKeyHint();
Expand Down
2 changes: 1 addition & 1 deletion NitroxClient/MonoBehaviours/NitroxBootstrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
6 changes: 3 additions & 3 deletions NitroxClient/MonoBehaviours/NitroxDebugManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
}
}
}
2 changes: 1 addition & 1 deletion NitroxClient/MonoBehaviours/PowerMonitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions NitroxClient/Unity/Helper/DebugUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -61,7 +61,7 @@ private static void ListComponents(GameObject gameObject, string linePrefix = ""
Component[] allComponents = gameObject.GetComponents<Component>();
foreach (Component c in allComponents)
{
Log.Debug("{0} =Component NAME={1}", linePrefix, c.GetType().Name);
Log.Debug($"{linePrefix}=Component NAME={c.GetType().Name}");
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions NitroxLauncher/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}

Expand Down
Loading

0 comments on commit 92e6549

Please sign in to comment.