Skip to content

Commit 0a001ca

Browse files
committed
Update naming and move to a Logging namespace
1 parent f5967dc commit 0a001ca

11 files changed

Lines changed: 152 additions & 129 deletions

com.unity.netcode.gameobjects/Editor/NetworkManagerEditor.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.IO;
44
using System.Linq;
55
using Unity.Netcode.Editor.Configuration;
6+
using Unity.Netcode.Logging;
67
using UnityEditor;
78
using UnityEngine;
89
#if UNITY_6000_5_OR_NEWER
@@ -298,7 +299,7 @@ private void DisplayNetworkManagerProperties()
298299
#else
299300
string path = Path.Combine(directory, $"NetworkPrefabs-{m_NetworkManager.GetInstanceID()}.asset");
300301
#endif
301-
m_NetworkManager.Log.Info(new Context(LogLevel.Normal, "Saving migrated Network Prefabs List").With("Path", path));
302+
m_NetworkManager.Log.Info(new Context(LogLevel.Normal, "Saving migrated Network Prefabs List").AddInfo("Path", path));
302303
AssetDatabase.CreateAsset(networkPrefabs, path);
303304
EditorUtility.SetDirty(m_NetworkManager);
304305
}

com.unity.netcode.gameobjects/Editor/NetworkManagerHelper.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.Collections.Generic;
22
using System.Linq;
33
using Unity.Netcode.Editor.Configuration;
4+
using Unity.Netcode.Logging;
45
using UnityEditor;
56
using UnityEngine;
67
using UnityEngine.SceneManagement;

com.unity.netcode.gameobjects/Runtime/Core/NetworkManager.cs

Lines changed: 13 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Unity.Collections;
44
using System.Linq;
55
using Unity.Netcode.Components;
6+
using Unity.Netcode.Logging;
67
using Unity.Netcode.Runtime;
78
using UnityEngine;
89
#if UNITY_EDITOR
@@ -73,7 +74,7 @@ internal static void LogSerializedTypeNotOptimized<T>()
7374
if (!s_SerializedType.Contains(type))
7475
{
7576
s_SerializedType.Add(type);
76-
NetworkLog.LogWarning(new Context(LogLevel.Developer, "Serialized type has not been optimized for use with Distributed Authority!").With(type.Name));
77+
NetworkLog.LogWarning(new Context(LogLevel.Developer, "Serialized type has not been optimized for use with Distributed Authority!").AddTag(type.Name));
7778
}
7879
}
7980
#endif
@@ -242,12 +243,12 @@ internal void PromoteSessionOwner(ulong clientId)
242243
if (!DistributedAuthorityMode)
243244
{
244245
// [Netcode] [PromoteSessionOwner][SceneManagement][NotDA] Invoking promote session owner while not in distributed authority mode!
245-
Log.ErrorServer(new Context(LogLevel.Error, "Invoking promote session owner while not in distributed authority mode!").With("SceneManagement").With("NotDA"));
246+
Log.ErrorServer(new Context(LogLevel.Error, "Invoking promote session owner while not in distributed authority mode!").AddTag("SceneManagement").AddTag("NotDA"));
246247
return;
247248
}
248249
if (!DAHost)
249250
{
250-
Log.ErrorServer(new Context(LogLevel.Error, "Client is attempting to promote another client as the session owner!").With("SceneManagement").With("NotDAHost"));
251+
Log.ErrorServer(new Context(LogLevel.Error, "Client is attempting to promote another client as the session owner!").AddTag("SceneManagement").AddTag("NotDAHost"));
251252
return;
252253
}
253254
SetSessionOwner(clientId);
@@ -315,7 +316,7 @@ private void UpdateTopology()
315316
if (transportTopology != NetworkConfig.NetworkTopology)
316317
{
317318
Log.ErrorServer(new Context(LogLevel.Error, "Transport detected an issue with the topology usage or setting! Disconnecting from session.")
318-
.With("Topology Mismatch").With(transportTopology, transportTopology.GetType().Name).With("NetworkManager.NetworkConfig", NetworkConfig.NetworkTopology));
319+
.AddTag("Topology Mismatch").AddInfo(transportTopology, transportTopology.GetType().Name).AddInfo("NetworkManager.NetworkConfig", NetworkConfig.NetworkTopology));
319320
Shutdown(true);
320321
}
321322
else
@@ -1054,10 +1055,10 @@ private void Awake()
10541055
{
10551056
if (Log == null)
10561057
{
1057-
Log = new ContextualLogger(this, gameObject);
1058+
Log = new ContextualLogger(this, this);
10581059
}
10591060

1060-
NetworkConfig?.InitializePrefabs();
1061+
NetworkConfig?.InitializePrefabs(Log);
10611062

10621063
UnityEngine.SceneManagement.SceneManager.sceneUnloaded += OnSceneUnloaded;
10631064
#if UNITY_EDITOR
@@ -1263,7 +1264,7 @@ internal void Initialize(bool server)
12631264
BehaviourUpdater = new NetworkBehaviourUpdater();
12641265
BehaviourUpdater.Initialize(this);
12651266

1266-
NetworkConfig.InitializePrefabs();
1267+
NetworkConfig.InitializePrefabs(Log);
12671268
PrefabHandler.RegisterPlayerPrefab();
12681269
#if UNITY_EDITOR
12691270
BeginNetworkSession();
@@ -1285,7 +1286,7 @@ private bool CanStart(StartType type)
12851286
{
12861287
if (IsListening)
12871288
{
1288-
Log.Warning(new Context(LogLevel.Normal, "Can't start while listening").With("Start", type));
1289+
Log.Warning(new Context(LogLevel.Normal, "Can't start while listening").AddInfo("Start", type));
12891290
return false;
12901291
}
12911292

@@ -1295,15 +1296,15 @@ private bool CanStart(StartType type)
12951296
{
12961297
if (ConnectionApprovalCallback == null)
12971298
{
1298-
Log.Warning(new Context(LogLevel.Normal, $"No {nameof(ConnectionApprovalCallback)} defined. Connection approval will timeout").With("Start", type));
1299+
Log.Warning(new Context(LogLevel.Normal, $"No {nameof(ConnectionApprovalCallback)} defined. Connection approval will timeout").AddInfo("Start", type));
12991300
}
13001301
}
13011302

13021303
if (ConnectionApprovalCallback != null)
13031304
{
13041305
if (!NetworkConfig.ConnectionApproval)
13051306
{
1306-
Log.Warning(new Context(LogLevel.Normal, $"{nameof(ConnectionApprovalCallback)} is defined but {nameof(NetworkConfig.ConnectionApproval)} is disabled. In order to use ConnectionApproval it has to be explicitly enabled").With("Start", type));
1307+
Log.Warning(new Context(LogLevel.Normal, $"{nameof(ConnectionApprovalCallback)} is defined but {nameof(NetworkConfig.ConnectionApproval)} is disabled. In order to use ConnectionApproval it has to be explicitly enabled").AddInfo("Start", type));
13071308
}
13081309
}
13091310

@@ -1725,7 +1726,7 @@ private void OnApplicationQuit()
17251726
#if UNITY_EDITOR
17261727
if (Singleton != null)
17271728
{
1728-
Log.Warning(new Context(LogLevel.Error, $"Singleton is not null after invoking OnDestroy. Do you have more than one {nameof(NetworkManager)} instance in the DDOL scene?").With("SingletonInstance", Singleton.name));
1729+
Log.Warning(new Context(LogLevel.Error, $"Singleton is not null after invoking OnDestroy. Do you have more than one {nameof(NetworkManager)} instance in the DDOL scene?").AddInfo("SingletonInstance", Singleton.name));
17291730
}
17301731
#endif
17311732
}
@@ -1824,7 +1825,7 @@ internal void OnValidate()
18241825

18251826
if (Log == null)
18261827
{
1827-
Log = new ContextualLogger(this, gameObject);
1828+
Log = new ContextualLogger(this, this);
18281829
}
18291830

18301831
// Do a validation pass on NetworkConfig properties
@@ -1835,44 +1836,6 @@ internal void OnValidate()
18351836
Log.Warning(new Context(LogLevel.Normal, $"{nameof(NetworkManager)} cannot be a {nameof(NetworkObject)}."));
18361837
}
18371838

1838-
var activeScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene();
1839-
1840-
// If the scene is not dirty or the asset database is currently updating then we can skip updating the NetworkPrefab information
1841-
if (!activeScene.isDirty || EditorApplication.isUpdating)
1842-
{
1843-
return;
1844-
}
1845-
1846-
// During OnValidate we will always clear out NetworkPrefabOverrideLinks and rebuild it
1847-
NetworkConfig.Prefabs.NetworkPrefabOverrideLinks.Clear();
1848-
1849-
var prefabs = NetworkConfig.Prefabs.Prefabs;
1850-
// Check network prefabs and assign to dictionary for quick look up
1851-
foreach (var networkPrefab in prefabs)
1852-
{
1853-
var networkPrefabGo = networkPrefab?.Prefab;
1854-
if (networkPrefabGo == null)
1855-
{
1856-
continue;
1857-
}
1858-
1859-
var networkObject = networkPrefabGo.GetComponent<NetworkObject>();
1860-
if (networkObject == null)
1861-
{
1862-
Log.Warning(new Context(LogLevel.Normal, $"Cannot register prefab to {nameof(NetworkManager)}, missing a {nameof(NetworkObject)} component at its root").ForNetworkPrefab(networkPrefab));
1863-
continue;
1864-
}
1865-
1866-
{
1867-
var childNetworkObjects = new List<NetworkObject>();
1868-
networkPrefabGo.GetComponentsInChildren(true, childNetworkObjects);
1869-
if (childNetworkObjects.Count > 1) // total count = 1 root NetworkObject + n child NetworkObjects
1870-
{
1871-
Log.Warning(new Context(LogLevel.Normal, $"Prefab has child {nameof(NetworkObject)}(s) but they will not be spawned across the network (unsupported {nameof(NetworkPrefab)} setup)").ForNetworkPrefab(networkPrefab));
1872-
}
1873-
}
1874-
}
1875-
18761839
try
18771840
{
18781841
OnValidateComponent();

com.unity.netcode.gameobjects/Runtime/Logging/ContextualLogger.cs

Lines changed: 57 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,55 @@
22
using System.Diagnostics;
33
using System.Diagnostics.CodeAnalysis;
44
using System.Runtime.CompilerServices;
5-
using System.Text;
65
using UnityEngine;
76
using Debug = UnityEngine.Debug;
87
using LogType = UnityEngine.LogType;
8+
using Object = UnityEngine.Object;
99

10-
namespace Unity.Netcode
10+
namespace Unity.Netcode.Logging
1111
{
12+
/// <summary>
13+
/// Configurable structured logger.
14+
/// Each logger instance collects system-wide context
15+
/// (e.g. which <see cref="Object"/> to attribute the logs to; or the <see cref="NetworkManager"/> relating to this object)
16+
/// Each log is made with a <see cref="Context"/> object that collects the local context of this individual log line
17+
/// The contextual logger will combine the system-wide context and the local context into one structured log message.
18+
/// </summary>
1219
internal class ContextualLogger
1320
{
1421
private const string k_NetcodeHeader = "[Netcode] ";
15-
private bool m_UseCompatibilityMode;
16-
private readonly GameObject m_GameObject;
17-
private readonly ContextBuilder m_Builder = new();
22+
private readonly bool m_UseCompatibilityMode;
23+
private readonly Object m_Object;
24+
private readonly LogBuilder m_Builder = new();
1825

1926
private LogContextNetworkManager m_ManagerContext;
2027
private readonly GenericContext m_LoggerContext;
2128

2229
private const string k_CompilationCondition = "UNITY_ASSERTIONS";
2330

31+
/// <summary>
32+
/// Creates a minimally configured contextual logger
33+
/// </summary>
34+
/// <param name="useCompatibilityMode">Suppresses adding </param>
2435
public ContextualLogger(bool useCompatibilityMode = false)
2536
{
2637
m_UseCompatibilityMode = useCompatibilityMode;
2738
m_ManagerContext = new LogContextNetworkManager(true);
28-
m_GameObject = null;
39+
m_Object = null;
2940
m_LoggerContext = GenericContext.Create();
3041
}
3142

32-
public ContextualLogger([NotNull] NetworkManager networkManager, GameObject gameObject)
43+
public ContextualLogger(Object inspectorObject)
44+
{
45+
m_ManagerContext = new LogContextNetworkManager(true);
46+
m_Object = inspectorObject;
47+
m_LoggerContext = GenericContext.Create();
48+
}
49+
50+
public ContextualLogger(Object inspectorObject, [NotNull] NetworkManager networkManager)
3351
{
3452
m_ManagerContext = new LogContextNetworkManager(networkManager);
35-
m_GameObject = gameObject;
53+
m_Object = inspectorObject;
3654
m_LoggerContext = GenericContext.Create();
3755
}
3856

@@ -44,24 +62,29 @@ internal void UpdateNetworkManagerContext(NetworkManager manager)
4462
}
4563

4664
[Conditional(k_CompilationCondition)]
47-
internal void PushContext(string key, object value)
65+
internal void AddInfo(string key, object value)
4866
{
4967
m_LoggerContext.StoreInfo(key, value);
5068
}
5169

52-
[Conditional(k_CompilationCondition)]
53-
internal void PushContext(string key)
70+
/// <summary>
71+
/// Adds info onto a logger that will be removed once the <see cref="DisposableContext"/> is disposed
72+
/// </summary>
73+
/// <param name="key">Key to log</param>
74+
/// <param name="value">Value to log</param>
75+
/// <returns>Object to dispose when context is no longer valid</returns>
76+
internal DisposableContext AddDisposableInfo(string key, object value)
5477
{
55-
m_LoggerContext.StoreContext(key);
78+
m_LoggerContext.StoreInfo(key, value);
79+
return new DisposableContext(this, key);
5680
}
5781

5882
[Conditional(k_CompilationCondition)]
59-
internal void PopContext(string key)
83+
internal void RemoveInfo(string key)
6084
{
6185
m_LoggerContext.ClearInfo(key);
6286
}
6387

64-
6588
[HideInCallstack]
6689
[Conditional(k_CompilationCondition)]
6790
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -93,7 +116,7 @@ public void CaptureFunctionCall([CallerMemberName] string memberName = "")
93116
[HideInCallstack]
94117
public void Exception(Exception exception)
95118
{
96-
Debug.unityLogger.LogException(exception, m_GameObject);
119+
Debug.unityLogger.LogException(exception, m_Object);
97120
}
98121

99122
[HideInCallstack]
@@ -106,7 +129,7 @@ private void Log(LogType logType, Context context)
106129
}
107130

108131
var message = BuildLog(context);
109-
Debug.unityLogger.Log(logType, (object)message, context.GameObjectOverride ?? m_GameObject);
132+
Debug.unityLogger.Log(logType, (object)message, context.RelevantObjectOverride ?? m_Object);
110133
}
111134

112135
[HideInCallstack]
@@ -119,9 +142,9 @@ private void LogServer(LogType logType, Context context)
119142
}
120143

121144
var message = BuildLog(context);
122-
Debug.unityLogger.Log(logType, (object)message, context.GameObjectOverride ?? m_GameObject);
145+
Debug.unityLogger.Log(logType, (object)message, context.RelevantObjectOverride ?? m_Object);
123146

124-
m_ManagerContext.TrySendMessage(logType, message);
147+
m_ManagerContext.TrySendMessage(logType, message.Remove(0, k_NetcodeHeader.Length));
125148
}
126149

127150
private string BuildLog(Context context)
@@ -132,7 +155,7 @@ private string BuildLog(Context context)
132155
m_Builder.Append(k_NetcodeHeader);
133156

134157
if (m_UseCompatibilityMode)
135-
{
158+
{ ;
136159
m_Builder.Append(context.Message);
137160
}
138161
else
@@ -147,38 +170,25 @@ private string BuildLog(Context context)
147170

148171
return m_Builder.Build();
149172
}
150-
}
151-
152-
internal class ContextBuilder
153-
{
154-
private readonly StringBuilder m_Builder = new();
155-
private const string k_OpenBracket = "[";
156-
private const string k_CloseBracket = "]";
157-
private const string k_Separator = ":";
158173

159-
public void Reset()
174+
/// <summary>
175+
/// Removes the configured context from the logger when this object is disposed.
176+
/// </summary>
177+
public readonly struct DisposableContext: IDisposable
160178
{
161-
m_Builder.Clear();
162-
}
179+
private readonly ContextualLogger m_Logger;
180+
private readonly string m_ToClear;
163181

164-
public void AppendContext(string context)
165-
{
166-
m_Builder.Append(k_OpenBracket);
167-
m_Builder.Append(context);
168-
m_Builder.Append(k_CloseBracket);
169-
}
182+
internal DisposableContext(ContextualLogger logger, string toClear)
183+
{
184+
m_Logger = logger;
185+
m_ToClear = toClear;
186+
}
170187

171-
public void AppendContext(object key, object value)
172-
{
173-
m_Builder.Append(k_OpenBracket);
174-
m_Builder.Append(key);
175-
m_Builder.Append(k_Separator);
176-
m_Builder.Append(value);
177-
m_Builder.Append(k_CloseBracket);
188+
public void Dispose()
189+
{
190+
m_Logger.RemoveInfo(m_ToClear);
191+
}
178192
}
179-
180-
public void Append(string value) => m_Builder.Append(value);
181-
182-
public string Build() => m_Builder.ToString();
183193
}
184194
}

0 commit comments

Comments
 (0)