Skip to content

Commit

Permalink
feat: NetworkIdentity use logger framework
Browse files Browse the repository at this point in the history
  • Loading branch information
paulpach committed Apr 26, 2020
1 parent 72154f1 commit 2e39e13
Showing 1 changed file with 39 additions and 37 deletions.
76 changes: 39 additions & 37 deletions Assets/Mirror/Runtime/NetworkIdentity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ namespace Mirror
[HelpURL("https://mirror-networking.com/docs/Components/NetworkIdentity.html")]
public sealed class NetworkIdentity : MonoBehaviour
{
static readonly ILogger logger = LogFactory.GetLogger<NetworkIdentity>();

// configuration
NetworkBehaviour[] networkBehavioursCache;

Expand Down Expand Up @@ -158,7 +160,7 @@ void CreateNetworkBehavioursCache()
networkBehavioursCache = GetComponents<NetworkBehaviour>();
if (NetworkBehaviours.Length > 64)
{
Debug.LogError($"Only 64 NetworkBehaviour components are allowed for NetworkIdentity: {name} because of the dirtyComponentMask", this);
logger.LogError($"Only 64 NetworkBehaviour components are allowed for NetworkIdentity: {name} because of the dirtyComponentMask", this);
// Log error once then resize array so that NetworkIdentity does not throw exceptions later
Array.Resize(ref networkBehavioursCache, 64);
}
Expand Down Expand Up @@ -213,7 +215,7 @@ internal set
{
m_AssetId = newAssetIdString;
}
else Debug.LogWarning($"SetDynamicAssetId object {name} already has an assetId {m_AssetId}, new asset id {newAssetIdString}");
else logger.LogWarning($"SetDynamicAssetId object {name} already has an assetId {m_AssetId}, new asset id {newAssetIdString}");
}
}

Expand All @@ -233,7 +235,7 @@ internal void SetClientOwner(NetworkConnection conn)
// do nothing if it already has an owner
if (connectionToClient != null && conn != connectionToClient)
{
Debug.LogError($"Object {this} netId={netId} already has an owner. Use RemoveClientAuthority() first", this);
logger.LogError($"Object {this} netId={netId} already has an owner. Use RemoveClientAuthority() first", this);
return;
}

Expand Down Expand Up @@ -288,7 +290,7 @@ void Awake()
{
if (sceneIds.TryGetValue(sceneId, out NetworkIdentity existing) && existing != this)
{
Debug.LogError(name + "'s sceneId: " + sceneId.ToString("X") + " is already taken by: " + existing.name + ". Don't call Instantiate for NetworkIdentities that were in the scene since the beginning (aka scene objects). Otherwise the client won't know which object to use for a SpawnSceneObject message.");
logger.LogError(name + "'s sceneId: " + sceneId.ToString("X") + " is already taken by: " + existing.name + ". Don't call Instantiate for NetworkIdentities that were in the scene since the beginning (aka scene objects). Otherwise the client won't know which object to use for a SpawnSceneObject message.");
Destroy(gameObject);
}
else
Expand Down Expand Up @@ -323,7 +325,7 @@ bool ThisIsASceneObjectWithPrefabParent(out GameObject prefab)

if (prefab == null)
{
Debug.LogError("Failed to find prefab parent for scene object [name:" + gameObject.name + "]");
logger.LogError("Failed to find prefab parent for scene object [name:" + gameObject.name + "]");
return false;
}
return true;
Expand Down Expand Up @@ -426,7 +428,7 @@ void AssignSceneID()
if (!duplicate)
{
sceneId = randomId;
//Debug.Log(name + " in scene=" + gameObject.scene.name + " sceneId assigned to: " + m_SceneId.ToString("X"));
//logger.Log(name + " in scene=" + gameObject.scene.name + " sceneId assigned to: " + m_SceneId.ToString("X"));
}
}

Expand Down Expand Up @@ -460,7 +462,7 @@ public void SetSceneIdSceneHashPartInternal()
sceneId = (sceneId & 0xFFFFFFFF) | shiftedHash;

// log it. this is incredibly useful to debug sceneId issues.
if (LogFilter.Debug) Debug.Log(name + " in scene=" + gameObject.scene.name + " scene index hash(" + pathHash.ToString("X") + ") copied into sceneId: " + sceneId.ToString("X"));
if (logger.LogEnabled()) logger.Log(name + " in scene=" + gameObject.scene.name + " scene index hash(" + pathHash.ToString("X") + ") copied into sceneId: " + sceneId.ToString("X"));
}

void SetupIDs()
Expand Down Expand Up @@ -493,7 +495,7 @@ void SetupIDs()
{
// force 0 for prefabs
sceneId = 0;
//Debug.Log(name + " @ scene: " + gameObject.scene.name + " sceneid reset to 0 because CurrentPrefabStage=" + PrefabStageUtility.GetCurrentPrefabStage() + " PrefabStage=" + PrefabStageUtility.GetPrefabStage(gameObject));
//logger.Log(name + " @ scene: " + gameObject.scene.name + " sceneid reset to 0 because CurrentPrefabStage=" + PrefabStageUtility.GetCurrentPrefabStage() + " PrefabStage=" + PrefabStageUtility.GetPrefabStage(gameObject));
// NOTE: might make sense to use GetPrefabStage for asset
// path, but let's not touch it while it works.
string path = PrefabStageUtility.GetCurrentPrefabStage().prefabAssetPath;
Expand Down Expand Up @@ -557,7 +559,7 @@ internal void OnStartServer()
netId = GetNextNetworkId();
observers = new Dictionary<int, NetworkConnection>();

if (LogFilter.Debug) Debug.Log("OnStartServer " + this + " NetId:" + netId + " SceneId:" + sceneId);
if (logger.LogEnabled()) logger.Log("OnStartServer " + this + " NetId:" + netId + " SceneId:" + sceneId);

// add to spawned (note: the original EnableIsServer isn't needed
// because we already set m_isServer=true above)
Expand All @@ -583,7 +585,7 @@ internal void OnStartServer()
}
catch (Exception e)
{
Debug.LogError("Exception in OnStartServer:" + e.Message + " " + e.StackTrace);
logger.LogError("Exception in OnStartServer:" + e.Message + " " + e.StackTrace);
}
}
}
Expand All @@ -603,7 +605,7 @@ internal void OnStopServer()
}
catch (Exception e)
{
Debug.LogError("Exception in OnStopServer:" + e.Message + " " + e.StackTrace);
logger.LogError("Exception in OnStopServer:" + e.Message + " " + e.StackTrace);
}
}
}
Expand All @@ -617,7 +619,7 @@ internal void OnStartClient()

isClient = true;

if (LogFilter.Debug) Debug.Log("OnStartClient " + gameObject + " netId:" + netId);
if (logger.LogEnabled()) logger.Log("OnStartClient " + gameObject + " netId:" + netId);
foreach (NetworkBehaviour comp in NetworkBehaviours)
{
// an exception in OnStartClient should be caught, so that one
Expand All @@ -632,7 +634,7 @@ internal void OnStartClient()
}
catch (Exception e)
{
Debug.LogError("Exception in OnStartClient:" + e.Message + " " + e.StackTrace);
logger.LogError("Exception in OnStartClient:" + e.Message + " " + e.StackTrace);
}
}
}
Expand All @@ -657,7 +659,7 @@ internal void OnStartLocalPlayer()
}
catch (Exception e)
{
Debug.LogError("Exception in OnStartLocalPlayer:" + e.Message + " " + e.StackTrace);
logger.LogError("Exception in OnStartLocalPlayer:" + e.Message + " " + e.StackTrace);
}
}
}
Expand Down Expand Up @@ -687,7 +689,7 @@ internal void OnStartAuthority()
}
catch (Exception e)
{
Debug.LogError("Exception in OnStartAuthority:" + e.Message + " " + e.StackTrace);
logger.LogError("Exception in OnStartAuthority:" + e.Message + " " + e.StackTrace);
}
}
}
Expand All @@ -707,7 +709,7 @@ internal void OnStopAuthority()
}
catch (Exception e)
{
Debug.LogError("Exception in OnStopAuthority:" + e.Message + " " + e.StackTrace);
logger.LogError("Exception in OnStopAuthority:" + e.Message + " " + e.StackTrace);
}
}
}
Expand All @@ -722,7 +724,7 @@ internal void OnSetHostVisibility(bool visible)
}
catch (Exception e)
{
Debug.LogError("Exception in OnSetLocalVisibility:" + e.Message + " " + e.StackTrace);
logger.LogError("Exception in OnSetLocalVisibility:" + e.Message + " " + e.StackTrace);
}
}
}
Expand All @@ -741,7 +743,7 @@ internal bool OnCheckObserver(NetworkConnection conn)
}
catch (Exception e)
{
Debug.LogError("Exception in OnCheckObserver:" + e.Message + " " + e.StackTrace);
logger.LogError("Exception in OnCheckObserver:" + e.Message + " " + e.StackTrace);
}
}
return true;
Expand All @@ -762,7 +764,7 @@ internal void OnStopClient()
}
catch (Exception e)
{
Debug.LogError("Exception in OnNetworkDestroy:" + e.Message + " " + e.StackTrace);
logger.LogError("Exception in OnNetworkDestroy:" + e.Message + " " + e.StackTrace);
}
isServer = false;
}
Expand Down Expand Up @@ -791,7 +793,7 @@ bool OnSerializeSafely(NetworkBehaviour comp, NetworkWriter writer, bool initial
catch (Exception e)
{
// show a detailed error and let the user know what went wrong
Debug.LogError("OnSerialize failed for: object=" + name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + "\n\n" + e);
logger.LogError("OnSerialize failed for: object=" + name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + "\n\n" + e);
}
int endPosition = writer.Position;

Expand All @@ -800,7 +802,7 @@ bool OnSerializeSafely(NetworkBehaviour comp, NetworkWriter writer, bool initial
writer.WriteInt32(endPosition - contentPosition);
writer.Position = endPosition;

if (LogFilter.Debug) Debug.Log("OnSerializeSafely written for object=" + comp.name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + "header@" + headerPosition + " content@" + contentPosition + " end@" + endPosition + " contentSize=" + (endPosition - contentPosition));
if (logger.LogEnabled()) logger.Log("OnSerializeSafely written for object=" + comp.name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + "header@" + headerPosition + " content@" + contentPosition + " end@" + endPosition + " contentSize=" + (endPosition - contentPosition));

return result;
}
Expand Down Expand Up @@ -840,7 +842,7 @@ internal void OnSerializeAllSafely(bool initialState, ulong dirtyComponentsMask,
// -> note: IsDirty() is false if the component isn't dirty or sendInterval isn't elapsed yet
if (initialState || comp.IsDirty())
{
if (LogFilter.Debug) Debug.Log("OnSerializeAllSafely: " + name + " -> " + comp.GetType() + " initial=" + initialState);
if (logger.LogEnabled()) logger.Log("OnSerializeAllSafely: " + name + " -> " + comp.GetType() + " initial=" + initialState);

// serialize into ownerWriter first
// (owner always gets everything!)
Expand Down Expand Up @@ -926,13 +928,13 @@ void OnDeserializeSafely(NetworkBehaviour comp, NetworkReader reader, bool initi
// way to mess up another component's deserialization
try
{
if (LogFilter.Debug) Debug.Log("OnDeserializeSafely: " + comp.name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + " length=" + contentSize);
if (logger.LogEnabled()) logger.Log("OnDeserializeSafely: " + comp.name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + " length=" + contentSize);
comp.OnDeserialize(reader, initialState);
}
catch (Exception e)
{
// show a detailed error and let the user know what went wrong
Debug.LogError("OnDeserialize failed for: object=" + name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + " length=" + contentSize + ". Possible Reasons:\n * Do " + comp.GetType() + "'s OnSerialize and OnDeserialize calls write the same amount of data(" + contentSize + " bytes)? \n * Was there an exception in " + comp.GetType() + "'s OnSerialize/OnDeserialize code?\n * Are the server and client the exact same project?\n * Maybe this OnDeserialize call was meant for another GameObject? The sceneIds can easily get out of sync if the Hierarchy was modified only in the client OR the server. Try rebuilding both.\n\n" + e);
logger.LogError("OnDeserialize failed for: object=" + name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + " length=" + contentSize + ". Possible Reasons:\n * Do " + comp.GetType() + "'s OnSerialize and OnDeserialize calls write the same amount of data(" + contentSize + " bytes)? \n * Was there an exception in " + comp.GetType() + "'s OnSerialize/OnDeserialize code?\n * Are the server and client the exact same project?\n * Maybe this OnDeserialize call was meant for another GameObject? The sceneIds can easily get out of sync if the Hierarchy was modified only in the client OR the server. Try rebuilding both.\n\n" + e);
}

// now the reader should be EXACTLY at 'before + size'.
Expand All @@ -941,7 +943,7 @@ void OnDeserializeSafely(NetworkBehaviour comp, NetworkReader reader, bool initi
{
// warn the user
int bytesRead = reader.Position - chunkStart;
Debug.LogWarning("OnDeserialize was expected to read " + contentSize + " instead of " + bytesRead + " bytes for object:" + name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + ". Make sure that OnSerialize and OnDeserialize write/read the same amount of data in all cases.");
logger.LogWarning("OnDeserialize was expected to read " + contentSize + " instead of " + bytesRead + " bytes for object:" + name + " component=" + comp.GetType() + " sceneId=" + sceneId.ToString("X") + ". Make sure that OnSerialize and OnDeserialize write/read the same amount of data in all cases.");

// fix the position, so the following components don't all fail
reader.Position = chunkEnd;
Expand Down Expand Up @@ -971,7 +973,7 @@ void HandleRemoteCall(int componentIndex, int functionHash, MirrorInvokeType inv
{
if (gameObject == null)
{
Debug.LogWarning(invokeType + " [" + functionHash + "] received for deleted object [netId=" + netId + "]");
logger.LogWarning(invokeType + " [" + functionHash + "] received for deleted object [netId=" + netId + "]");
return;
}

Expand All @@ -981,12 +983,12 @@ void HandleRemoteCall(int componentIndex, int functionHash, MirrorInvokeType inv
NetworkBehaviour invokeComponent = NetworkBehaviours[componentIndex];
if (!invokeComponent.InvokeHandlerDelegate(functionHash, invokeType, reader))
{
Debug.LogError("Found no receiver for incoming " + invokeType + " [" + functionHash + "] on " + gameObject + ", the server and client should have the same NetworkBehaviour instances [netId=" + netId + "].");
logger.LogError("Found no receiver for incoming " + invokeType + " [" + functionHash + "] on " + gameObject + ", the server and client should have the same NetworkBehaviour instances [netId=" + netId + "].");
}
}
else
{
Debug.LogWarning("Component [" + componentIndex + "] not found for [netId=" + netId + "]");
logger.LogWarning("Component [" + componentIndex + "] not found for [netId=" + netId + "]");
}
}

Expand Down Expand Up @@ -1024,7 +1026,7 @@ internal void AddObserver(NetworkConnection conn)
{
if (observers == null)
{
Debug.LogError("AddObserver for " + gameObject + " observer list is null");
logger.LogError("AddObserver for " + gameObject + " observer list is null");
return;
}

Expand All @@ -1035,7 +1037,7 @@ internal void AddObserver(NetworkConnection conn)
return;
}

if (LogFilter.Debug) Debug.Log("Added observer " + conn.address + " added for " + gameObject);
if (logger.LogEnabled()) logger.Log("Added observer " + conn.address + " added for " + gameObject);

observers[conn.connectionId] = conn;
conn.AddToVisList(this);
Expand Down Expand Up @@ -1129,7 +1131,7 @@ public void RebuildObservers(bool initialize)
{
// new observer
conn.AddToVisList(this);
if (LogFilter.Debug) Debug.Log("New Observer for " + gameObject + " " + conn);
if (logger.LogEnabled()) logger.Log("New Observer for " + gameObject + " " + conn);
changed = true;
}
}
Expand All @@ -1142,7 +1144,7 @@ public void RebuildObservers(bool initialize)
{
// removed observer
conn.RemoveFromVisList(this, false);
if (LogFilter.Debug) Debug.Log("Removed Observer for " + gameObject + " " + conn);
if (logger.LogEnabled()) logger.Log("Removed Observer for " + gameObject + " " + conn);
changed = true;
}
}
Expand Down Expand Up @@ -1198,19 +1200,19 @@ public bool AssignClientAuthority(NetworkConnection conn)
{
if (!isServer)
{
Debug.LogError("AssignClientAuthority can only be called on the server for spawned objects.");
logger.LogError("AssignClientAuthority can only be called on the server for spawned objects.");
return false;
}

if (conn == null)
{
Debug.LogError("AssignClientAuthority for " + gameObject + " owner cannot be null. Use RemoveClientAuthority() instead.");
logger.LogError("AssignClientAuthority for " + gameObject + " owner cannot be null. Use RemoveClientAuthority() instead.");
return false;
}

if (connectionToClient != null && conn != connectionToClient)
{
Debug.LogError("AssignClientAuthority for " + gameObject + " already has an owner. Use RemoveClientAuthority() first.");
logger.LogError("AssignClientAuthority for " + gameObject + " already has an owner. Use RemoveClientAuthority() first.");
return false;
}

Expand All @@ -1234,13 +1236,13 @@ public void RemoveClientAuthority()
{
if (!isServer)
{
Debug.LogError("RemoveClientAuthority can only be called on the server for spawned objects.");
logger.LogError("RemoveClientAuthority can only be called on the server for spawned objects.");
return;
}

if (connectionToClient?.identity == this)
{
Debug.LogError("RemoveClientAuthority cannot remove authority for a player object");
logger.LogError("RemoveClientAuthority cannot remove authority for a player object");
return;
}

Expand Down

0 comments on commit 2e39e13

Please sign in to comment.