From b4c69e08dc396511281fe3b55d55f858779ebf60 Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:11:57 +0300 Subject: [PATCH 01/42] rename: message type enum --- UnityPackage/Editor/Window/ConsoleViewer.cs | 4 +-- UnityPackage/Runtime/ConsoleInstance.cs | 32 +++++++++---------- UnityPackage/Runtime/ConsoleMessage.cs | 4 +-- UnityPackage/Runtime/ConsoleMessageType.cs | 10 ++++++ ...ype.cs.meta => ConsoleMessageType.cs.meta} | 0 UnityPackage/Runtime/IConsoleInstance.cs | 2 +- UnityPackage/Runtime/MessageType.cs | 9 ------ .../Runtime/UnityConsoleForwarding.cs | 14 ++++---- 8 files changed, 38 insertions(+), 37 deletions(-) create mode 100644 UnityPackage/Runtime/ConsoleMessageType.cs rename UnityPackage/Runtime/{MessageType.cs.meta => ConsoleMessageType.cs.meta} (100%) delete mode 100644 UnityPackage/Runtime/MessageType.cs diff --git a/UnityPackage/Editor/Window/ConsoleViewer.cs b/UnityPackage/Editor/Window/ConsoleViewer.cs index 0fc868b..de8da4b 100644 --- a/UnityPackage/Editor/Window/ConsoleViewer.cs +++ b/UnityPackage/Editor/Window/ConsoleViewer.cs @@ -342,8 +342,8 @@ private VisualElement CreateRow(ConsoleMessage message) { VisualTreeAsset asset = message.Type switch { - MessageType.Warning => messageWarningAsset, - MessageType.Error => messageErrorAsset, + ConsoleMessageType.Warning => messageWarningAsset, + ConsoleMessageType.Error => messageErrorAsset, _ => messageTextAsset }; diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index bf9091a..a37364e 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -89,7 +89,7 @@ public sealed class ConsoleInstance : IConsoleInstance, IDisposable public event Action MessageCreated; /// - /// Raised only for messages, right after + /// Raised only for messages, right after /// . Convenience for the common case of /// reacting to failures without filtering by type; the same threading and /// exception rules as apply. @@ -133,22 +133,22 @@ public ConsoleInstance(string name) } public void CreateText(object source, params string[] messageContent) - => Create(MessageType.Text, ResolveSource(source), messageContent); + => Create(ConsoleMessageType.Text, ResolveSource(source), messageContent); public void CreateText(string source, params string[] messageContent) - => Create(MessageType.Text, ResolveSource(source), messageContent); + => Create(ConsoleMessageType.Text, ResolveSource(source), messageContent); public void CreateWarning(object source, params string[] messageContent) - => Create(MessageType.Warning, ResolveSource(source), messageContent); + => Create(ConsoleMessageType.Warning, ResolveSource(source), messageContent); public void CreateWarning(string source, params string[] messageContent) - => Create(MessageType.Warning, ResolveSource(source), messageContent); + => Create(ConsoleMessageType.Warning, ResolveSource(source), messageContent); public void CreateError(object source, params string[] messageContent) - => Create(MessageType.Error, ResolveSource(source), messageContent); + => Create(ConsoleMessageType.Error, ResolveSource(source), messageContent); public void CreateError(string source, params string[] messageContent) - => Create(MessageType.Error, ResolveSource(source), messageContent); + => Create(ConsoleMessageType.Error, ResolveSource(source), messageContent); /// /// Removes every message from this instance. Clearing an already disposed @@ -214,7 +214,7 @@ public void Dispose() #endif } - private void Create(MessageType type, string source, string[] messageContent) + private void Create(ConsoleMessageType type, string source, string[] messageContent) { if (IsDisposed) { @@ -256,11 +256,11 @@ private void Create(MessageType type, string source, string[] messageContent) #endif } - private void RaiseCreated(MessageType type, ConsoleMessage message) + private void RaiseCreated(ConsoleMessageType type, ConsoleMessage message) { Invoke(MessageCreated, message); - if (type == MessageType.Error) + if (type == ConsoleMessageType.Error) { Invoke(ErrorCreated, message); } @@ -311,19 +311,19 @@ private static void Invoke(Action handler, ConsoleMessage messag } } - private static void ForwardToUnityConsole(MessageType type, string source, string content) + private static void ForwardToUnityConsole(ConsoleMessageType type, string source, string content) { string formatted = $"{source}: {content}"; switch (type) { - case MessageType.Text: + case ConsoleMessageType.Text: Debug.Log(formatted); break; - case MessageType.Warning: + case ConsoleMessageType.Warning: Debug.LogWarning(formatted); break; - case MessageType.Error: + case ConsoleMessageType.Error: Debug.LogError(formatted); break; } @@ -437,8 +437,8 @@ private static string ResolveMethodName(Type declaringType, System.Reflection.Me #else // Cheap pre-check that keeps a build from allocating a ConsoleMessage // nobody would receive. - private bool HasListener(MessageType type) - => MessageCreated != null || (type == MessageType.Error && ErrorCreated != null); + private bool HasListener(ConsoleMessageType type) + => MessageCreated != null || (type == ConsoleMessageType.Error && ErrorCreated != null); #endif } } diff --git a/UnityPackage/Runtime/ConsoleMessage.cs b/UnityPackage/Runtime/ConsoleMessage.cs index 0caf99b..d91ea4c 100644 --- a/UnityPackage/Runtime/ConsoleMessage.cs +++ b/UnityPackage/Runtime/ConsoleMessage.cs @@ -20,7 +20,7 @@ public sealed class ConsoleMessage /// public long Sequence { get; } - public MessageType Type { get; } + public ConsoleMessageType Type { get; } public DateTime Timestamp { get; } @@ -33,7 +33,7 @@ public sealed class ConsoleMessage /// Source-resolvable call stack, innermost caller first. Empty in player builds. public IReadOnlyList Callstack { get; } - public ConsoleMessage(MessageType type, string source, string content, IReadOnlyList callstack) + public ConsoleMessage(ConsoleMessageType type, string source, string content, IReadOnlyList callstack) { Timestamp = DateTime.Now; Sequence = Interlocked.Increment(ref _globalSequence); diff --git a/UnityPackage/Runtime/ConsoleMessageType.cs b/UnityPackage/Runtime/ConsoleMessageType.cs new file mode 100644 index 0000000..0ead168 --- /dev/null +++ b/UnityPackage/Runtime/ConsoleMessageType.cs @@ -0,0 +1,10 @@ +namespace reromanlee.ConsoleContainer +{ + /// Severity of a . + public enum ConsoleMessageType + { + Text = 0, + Warning = 1, + Error = 2 + } +} diff --git a/UnityPackage/Runtime/MessageType.cs.meta b/UnityPackage/Runtime/ConsoleMessageType.cs.meta similarity index 100% rename from UnityPackage/Runtime/MessageType.cs.meta rename to UnityPackage/Runtime/ConsoleMessageType.cs.meta diff --git a/UnityPackage/Runtime/IConsoleInstance.cs b/UnityPackage/Runtime/IConsoleInstance.cs index 6fb70c4..8b1ce5f 100644 --- a/UnityPackage/Runtime/IConsoleInstance.cs +++ b/UnityPackage/Runtime/IConsoleInstance.cs @@ -17,7 +17,7 @@ public interface IConsoleInstance public event Action MessageCreated; /// - /// Raised for messages only, right after + /// Raised for messages only, right after /// . Lets application code react to a failure /// (for example by showing a soft-crash screen with the message as the /// reason) without inspecting every message's type. diff --git a/UnityPackage/Runtime/MessageType.cs b/UnityPackage/Runtime/MessageType.cs deleted file mode 100644 index 4d48533..0000000 --- a/UnityPackage/Runtime/MessageType.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace reromanlee.ConsoleContainer -{ - public enum MessageType - { - Text, - Warning, - Error - } -} \ No newline at end of file diff --git a/UnityPackage/Runtime/UnityConsoleForwarding.cs b/UnityPackage/Runtime/UnityConsoleForwarding.cs index ef7b7b7..aed1733 100644 --- a/UnityPackage/Runtime/UnityConsoleForwarding.cs +++ b/UnityPackage/Runtime/UnityConsoleForwarding.cs @@ -32,7 +32,7 @@ internal static bool IsTestRunActive /// Safe to call from any thread: when the settings asset has not been /// cached yet on the main thread, the package defaults apply. /// - internal static bool ShouldForward(MessageType type) + internal static bool ShouldForward(ConsoleMessageType type) { ConsoleContainerSettings settings = ConsoleContainerSettings.Active; @@ -58,11 +58,11 @@ internal static bool ShouldForward(MessageType type) switch (type) { - case MessageType.Text: + case ConsoleMessageType.Text: return settings.LogTextInEditor; - case MessageType.Warning: + case ConsoleMessageType.Warning: return settings.LogWarningsInEditor; - case MessageType.Error: + case ConsoleMessageType.Error: return settings.LogErrorsInEditor; default: return false; @@ -76,11 +76,11 @@ internal static bool ShouldForward(MessageType type) switch (type) { - case MessageType.Text: + case ConsoleMessageType.Text: return settings.LogTextInBuild; - case MessageType.Warning: + case ConsoleMessageType.Warning: return settings.LogWarningsInBuild; - case MessageType.Error: + case ConsoleMessageType.Error: return settings.LogErrorsInBuild; default: return false; From b49343dd037349d9f58b0d2cd28d6d5f448df71a Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:14:17 +0300 Subject: [PATCH 02/42] refactor: core interface --- UnityPackage/Runtime/ConsoleInstance.cs | 141 +++++++++--------- .../Runtime/ConsoleInstanceExtensions.cs | 75 ++++++++++ .../Runtime/ConsoleInstanceExtensions.cs.meta | 2 + UnityPackage/Runtime/IConsoleInstance.cs | 39 +++-- 4 files changed, 176 insertions(+), 81 deletions(-) create mode 100644 UnityPackage/Runtime/ConsoleInstanceExtensions.cs create mode 100644 UnityPackage/Runtime/ConsoleInstanceExtensions.cs.meta diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index a37364e..cc6cb14 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -22,10 +22,14 @@ namespace reromanlee.ConsoleContainer /// static event reaches every instance at once, so a /// single subscriber can cover instances it never constructed. /// - /// Every Create* method is safe to call concurrently from any thread. + /// Every member is safe to call concurrently from any thread. Log through the + /// shortcuts (CreateText, + /// CreateWarning, CreateError). /// - public sealed class ConsoleInstance : IConsoleInstance, IDisposable + public sealed class ConsoleInstance : IConsoleInstance { + private const string MissingSource = "null"; + // Above this many entries, a cleared instance releases its backing array // instead of holding on to capacity it is unlikely to need again. private const int ClearedCapacityTrimThreshold = 1024; @@ -132,23 +136,75 @@ public ConsoleInstance(string name) RaiseCreated(this); } - public void CreateText(object source, params string[] messageContent) - => Create(ConsoleMessageType.Text, ResolveSource(source), messageContent); + /// + /// Whether a message of would have any effect right now; false once + /// disposed. The editor keeps every message for the viewer, while a player build only acts on + /// one that is forwarded to the Unity log or has a subscriber to receive it. + /// + public bool IsEnabled(ConsoleMessageType type) + { + if (IsDisposed) + { + return false; + } + +#if UNITY_EDITOR + return true; +#else + return HasListener(type) || UnityConsoleForwarding.ShouldForward(type); +#endif + } + + /// + /// Creates a message from an already resolved source name and content. Prefer the + /// shortcuts, which resolve the source and skip the + /// work entirely when the message type is disabled. + /// + /// Severity of the message. + /// Name of whatever produced the message; "null" when empty. + /// Message body. + public void Create(ConsoleMessageType type, string source, string content) + { + if (IsDisposed) + { + return; + } + + source = string.IsNullOrEmpty(source) ? MissingSource : source; + content ??= string.Empty; + +#if UNITY_EDITOR + // The editor keeps every message for the viewer, so the entry is + // always built. + ConsoleMessage message = new ConsoleMessage(type, source, content, CaptureCallstack()); - public void CreateText(string source, params string[] messageContent) - => Create(ConsoleMessageType.Text, ResolveSource(source), messageContent); + lock (_gate) + { + _messages.Add(message); + } - public void CreateWarning(object source, params string[] messageContent) - => Create(ConsoleMessageType.Warning, ResolveSource(source), messageContent); + ConsoleRegistry.NotifyMessageAdded(this); - public void CreateWarning(string source, params string[] messageContent) - => Create(ConsoleMessageType.Warning, ResolveSource(source), messageContent); + if (UnityConsoleForwarding.ShouldForward(type)) + { + ForwardToUnityConsole(type, source, content); + } - public void CreateError(object source, params string[] messageContent) - => Create(ConsoleMessageType.Error, ResolveSource(source), messageContent); + RaiseCreated(type, message); +#else + if (UnityConsoleForwarding.ShouldForward(type)) + { + ForwardToUnityConsole(type, source, content); + } - public void CreateError(string source, params string[] messageContent) - => Create(ConsoleMessageType.Error, ResolveSource(source), messageContent); + // Player builds keep no history, so the entry is only worth + // allocating when something is actually listening for it. + if (HasListener(type)) + { + RaiseCreated(type, new ConsoleMessage(type, source, content, null)); + } +#endif + } /// /// Removes every message from this instance. Clearing an already disposed @@ -214,48 +270,6 @@ public void Dispose() #endif } - private void Create(ConsoleMessageType type, string source, string[] messageContent) - { - if (IsDisposed) - { - return; - } - - string content = BuildContent(messageContent); - -#if UNITY_EDITOR - // The editor keeps every message for the viewer, so the entry is - // always built. - ConsoleMessage message = new ConsoleMessage(type, source, content, CaptureCallstack()); - - lock (_gate) - { - _messages.Add(message); - } - - ConsoleRegistry.NotifyMessageAdded(this); - - if (UnityConsoleForwarding.ShouldForward(type)) - { - ForwardToUnityConsole(type, source, content); - } - - RaiseCreated(type, message); -#else - if (UnityConsoleForwarding.ShouldForward(type)) - { - ForwardToUnityConsole(type, source, content); - } - - // Player builds keep no history, so the entry is only worth - // allocating when something is actually listening for it. - if (HasListener(type)) - { - RaiseCreated(type, new ConsoleMessage(type, source, content, null)); - } -#endif - } - private void RaiseCreated(ConsoleMessageType type, ConsoleMessage message) { Invoke(MessageCreated, message); @@ -329,17 +343,6 @@ private static void ForwardToUnityConsole(ConsoleMessageType type, string source } } - private static string ResolveSource(object source) - => source?.GetType().Name ?? "null"; - - private static string ResolveSource(string source) - => string.IsNullOrEmpty(source) ? "null" : source; - - private static string BuildContent(string[] messageContent) - => messageContent == null || messageContent.Length == 0 - ? string.Empty - : string.Join(" ", messageContent); - #if UNITY_EDITOR /// /// Copies messages created after into @@ -387,10 +390,10 @@ private static CallstackFrame[] CaptureCallstack() System.Reflection.MethodBase method = frame.GetMethod(); Type declaringType = method?.DeclaringType; - // Skip only this class's own logging methods so the top frame is + // Skip only the logging methods themselves so the top frame is // the caller's real log site. Filtering by the package namespace // would wrongly drop user code that lives under it (e.g. samples). - if (declaringType == typeof(ConsoleInstance)) + if (declaringType == typeof(ConsoleInstance) || declaringType == typeof(ConsoleInstanceExtensions)) { continue; } diff --git a/UnityPackage/Runtime/ConsoleInstanceExtensions.cs b/UnityPackage/Runtime/ConsoleInstanceExtensions.cs new file mode 100644 index 0000000..faa19dc --- /dev/null +++ b/UnityPackage/Runtime/ConsoleInstanceExtensions.cs @@ -0,0 +1,75 @@ +using System; + +namespace reromanlee.ConsoleContainer +{ + /// + /// Logging shortcuts for any . + /// + /// The source names whatever produced the message: a is used as is, + /// and any other object contributes its type name. Content arguments are joined with single + /// spaces. Nothing is built when the instance reports the message type as disabled. + /// + public static class ConsoleInstanceExtensions + { + private const string ContentSeparator = " "; + + public static void CreateText(this IConsoleInstance console, object source, string message) + => CreateSingle(console, ConsoleMessageType.Text, source, message); + + public static void CreateText(this IConsoleInstance console, object source, params string[] messageContent) + => CreateJoined(console, ConsoleMessageType.Text, source, messageContent); + + public static void CreateWarning(this IConsoleInstance console, object source, string message) + => CreateSingle(console, ConsoleMessageType.Warning, source, message); + + public static void CreateWarning(this IConsoleInstance console, object source, params string[] messageContent) + => CreateJoined(console, ConsoleMessageType.Warning, source, messageContent); + + public static void CreateError(this IConsoleInstance console, object source, string message) + => CreateSingle(console, ConsoleMessageType.Error, source, message); + + public static void CreateError(this IConsoleInstance console, object source, params string[] messageContent) + => CreateJoined(console, ConsoleMessageType.Error, source, messageContent); + + private static void CreateSingle(IConsoleInstance console, ConsoleMessageType type, object source, string message) + { + if (console == null) + { + throw new ArgumentNullException(nameof(console)); + } + + if (console.IsEnabled(type)) + { + console.Create(type, ResolveSource(source), message ?? string.Empty); + } + } + + private static void CreateJoined(IConsoleInstance console, ConsoleMessageType type, object source, string[] messageContent) + { + if (console == null) + { + throw new ArgumentNullException(nameof(console)); + } + + if (console.IsEnabled(type)) + { + console.Create(type, ResolveSource(source), Join(messageContent)); + } + } + + private static string ResolveSource(object source) + => source is string text ? text : source?.GetType().Name; + + private static string Join(string[] messageContent) + { + if (messageContent == null || messageContent.Length == 0) + { + return string.Empty; + } + + return messageContent.Length == 1 + ? messageContent[0] ?? string.Empty + : string.Join(ContentSeparator, messageContent); + } + } +} diff --git a/UnityPackage/Runtime/ConsoleInstanceExtensions.cs.meta b/UnityPackage/Runtime/ConsoleInstanceExtensions.cs.meta new file mode 100644 index 0000000..be78c34 --- /dev/null +++ b/UnityPackage/Runtime/ConsoleInstanceExtensions.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 80da465c916e8bd584bb200a7dc58bd8 diff --git a/UnityPackage/Runtime/IConsoleInstance.cs b/UnityPackage/Runtime/IConsoleInstance.cs index 8b1ce5f..2ba207a 100644 --- a/UnityPackage/Runtime/IConsoleInstance.cs +++ b/UnityPackage/Runtime/IConsoleInstance.cs @@ -3,18 +3,27 @@ namespace reromanlee.ConsoleContainer { /// - /// Defines a contract for creating text messages, warning - /// messages or error messages inside a container instance, and for - /// observing the messages it produces. + /// A named container of log messages that can be observed as messages are created. + /// + /// Implementations only provide the core members below. The CreateText, + /// CreateWarning and CreateError shortcuts live in + /// , so they work with any implementation and new + /// overloads never break one. /// - public interface IConsoleInstance + public interface IConsoleInstance : IDisposable { + /// Display name shown in the Console Viewer's instance dropdown. + string Name { get; } + + /// True once has been called; further messages are ignored. + bool IsDisposed { get; } + /// /// Raised for every created message, of any type. Raised on the logging /// thread — marshal to the main thread before touching Unity APIs — in /// both the editor and player builds. /// - public event Action MessageCreated; + event Action MessageCreated; /// /// Raised for messages only, right after @@ -22,15 +31,21 @@ public interface IConsoleInstance /// (for example by showing a soft-crash screen with the message as the /// reason) without inspecting every message's type. /// - public event Action ErrorCreated; + event Action ErrorCreated; - public void CreateText(object source, params string[] messageContent); - public void CreateText(string source, params string[] messageContent); + /// + /// Whether a message of would have any effect right now. Callers use it + /// to skip building message content that would only be thrown away. + /// + bool IsEnabled(ConsoleMessageType type); - public void CreateWarning(object source, params string[] messageContent); - public void CreateWarning(string source, params string[] messageContent); + /// Creates a message from an already resolved source name and content. + /// Severity of the message. + /// Name of whatever produced the message. + /// Message body. + void Create(ConsoleMessageType type, string source, string content); - public void CreateError(object source, params string[] messageContent); - public void CreateError(string source, params string[] messageContent); + /// Removes every message this instance holds. + void Clear(); } } From f98dae006e3e907cc8eb45f8eb2adc950638735b Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:14:52 +0300 Subject: [PATCH 03/42] fix: source name lookup --- .../Runtime/ConsoleInstanceExtensions.cs | 12 ++-- UnityPackage/Runtime/SourceNames.cs | 67 +++++++++++++++++++ UnityPackage/Runtime/SourceNames.cs.meta | 2 + 3 files changed, 74 insertions(+), 7 deletions(-) create mode 100644 UnityPackage/Runtime/SourceNames.cs create mode 100644 UnityPackage/Runtime/SourceNames.cs.meta diff --git a/UnityPackage/Runtime/ConsoleInstanceExtensions.cs b/UnityPackage/Runtime/ConsoleInstanceExtensions.cs index faa19dc..f2b8310 100644 --- a/UnityPackage/Runtime/ConsoleInstanceExtensions.cs +++ b/UnityPackage/Runtime/ConsoleInstanceExtensions.cs @@ -6,8 +6,9 @@ namespace reromanlee.ConsoleContainer /// Logging shortcuts for any . /// /// The source names whatever produced the message: a is used as is, - /// and any other object contributes its type name. Content arguments are joined with single - /// spaces. Nothing is built when the instance reports the message type as disabled. + /// a contributes its own name (handy in static classes), and any other object + /// contributes its type's name. Content arguments are joined with single spaces. Nothing is + /// built when the instance reports the message type as disabled. /// public static class ConsoleInstanceExtensions { @@ -40,7 +41,7 @@ private static void CreateSingle(IConsoleInstance console, ConsoleMessageType ty if (console.IsEnabled(type)) { - console.Create(type, ResolveSource(source), message ?? string.Empty); + console.Create(type, SourceNames.Resolve(source), message ?? string.Empty); } } @@ -53,13 +54,10 @@ private static void CreateJoined(IConsoleInstance console, ConsoleMessageType ty if (console.IsEnabled(type)) { - console.Create(type, ResolveSource(source), Join(messageContent)); + console.Create(type, SourceNames.Resolve(source), Join(messageContent)); } } - private static string ResolveSource(object source) - => source is string text ? text : source?.GetType().Name; - private static string Join(string[] messageContent) { if (messageContent == null || messageContent.Length == 0) diff --git a/UnityPackage/Runtime/SourceNames.cs b/UnityPackage/Runtime/SourceNames.cs new file mode 100644 index 0000000..9f4a575 --- /dev/null +++ b/UnityPackage/Runtime/SourceNames.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Concurrent; +using System.Text; + +namespace reromanlee.ConsoleContainer +{ + /// + /// Turns whatever a caller passes as a message source into a readable name: a string as is, a + /// by its own name (so static classes can pass typeof(...)), and any + /// other object by its type's name. Generic types read as List<Int32> instead of + /// List`1. Names are cached per type, so resolving a source allocates nothing after the + /// first time a type is seen. + /// + internal static class SourceNames + { + private static readonly ConcurrentDictionary Cache = new ConcurrentDictionary(); + + // Cached delegate: a method group passed to GetOrAdd would allocate on every call. + private static readonly Func Formatter = Format; + + internal static string Resolve(object source) + { + switch (source) + { + case null: + return null; + case string text: + return text; + case Type type: + return Of(type); + default: + return Of(source.GetType()); + } + } + + internal static string Of(Type type) => Cache.GetOrAdd(type, Formatter); + + private static string Format(Type type) + { + string name = type.Name; + if (!type.IsGenericType) + { + return name; + } + + int arityMarker = name.IndexOf('`'); + if (arityMarker > 0) + { + name = name.Substring(0, arityMarker); + } + + Type[] arguments = type.GetGenericArguments(); + StringBuilder builder = new StringBuilder(name).Append('<'); + for (int i = 0; i < arguments.Length; i++) + { + if (i > 0) + { + builder.Append(", "); + } + + builder.Append(Of(arguments[i])); + } + + return builder.Append('>').ToString(); + } + } +} diff --git a/UnityPackage/Runtime/SourceNames.cs.meta b/UnityPackage/Runtime/SourceNames.cs.meta new file mode 100644 index 0000000..2741817 --- /dev/null +++ b/UnityPackage/Runtime/SourceNames.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 60a635ce2e7a16719d3e2f811f8898d7 From 569cdd92ecb48db1df954a0210acad2501792e87 Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:15:29 +0300 Subject: [PATCH 04/42] fix: stable message text --- UnityPackage/Runtime/ConsoleInstance.cs | 14 ++++++------- UnityPackage/Runtime/ConsoleMessage.cs | 28 ++++++++++++++++++++----- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index cc6cb14..6edea0c 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -187,14 +187,14 @@ public void Create(ConsoleMessageType type, string source, string content) if (UnityConsoleForwarding.ShouldForward(type)) { - ForwardToUnityConsole(type, source, content); + ForwardToUnityConsole(type, message.Label); } RaiseCreated(type, message); #else if (UnityConsoleForwarding.ShouldForward(type)) { - ForwardToUnityConsole(type, source, content); + ForwardToUnityConsole(type, ConsoleMessage.ComposeLabel(source, content)); } // Player builds keep no history, so the entry is only worth @@ -325,20 +325,18 @@ private static void Invoke(Action handler, ConsoleMessage messag } } - private static void ForwardToUnityConsole(ConsoleMessageType type, string source, string content) + private static void ForwardToUnityConsole(ConsoleMessageType type, string label) { - string formatted = $"{source}: {content}"; - switch (type) { case ConsoleMessageType.Text: - Debug.Log(formatted); + Debug.Log(label); break; case ConsoleMessageType.Warning: - Debug.LogWarning(formatted); + Debug.LogWarning(label); break; case ConsoleMessageType.Error: - Debug.LogError(formatted); + Debug.LogError(label); break; } } diff --git a/UnityPackage/Runtime/ConsoleMessage.cs b/UnityPackage/Runtime/ConsoleMessage.cs index d91ea4c..f5c11c0 100644 --- a/UnityPackage/Runtime/ConsoleMessage.cs +++ b/UnityPackage/Runtime/ConsoleMessage.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Threading; namespace reromanlee.ConsoleContainer @@ -10,8 +11,17 @@ namespace reromanlee.ConsoleContainer /// public sealed class ConsoleMessage { + private const string TimeFormat = "[HH:mm:ss]"; + private const string LabelSeparator = ": "; + private static long _globalSequence; + // Derived text is built on first use and kept, so rows being re-bound or handlers + // formatting the same message allocate nothing more. Racing threads can only ever + // store equal strings, so no lock is needed. + private string label; + private string timeText; + /// /// Globally monotonic creation order. Because it is assigned atomically /// the moment a message is built, sorting several instances' messages by @@ -20,8 +30,10 @@ public sealed class ConsoleMessage /// public long Sequence { get; } + /// Severity of the message. public ConsoleMessageType Type { get; } + /// Local time at which the message was created. public DateTime Timestamp { get; } /// The resolved source name (a string, or an object's type name). @@ -33,7 +45,7 @@ public sealed class ConsoleMessage /// Source-resolvable call stack, innermost caller first. Empty in player builds. public IReadOnlyList Callstack { get; } - public ConsoleMessage(ConsoleMessageType type, string source, string content, IReadOnlyList callstack) + internal ConsoleMessage(ConsoleMessageType type, string source, string content, IReadOnlyList callstack) { Timestamp = DateTime.Now; Sequence = Interlocked.Increment(ref _globalSequence); @@ -43,10 +55,16 @@ public ConsoleMessage(ConsoleMessageType type, string source, string content, IR Callstack = callstack ?? Array.Empty(); } - /// Timestamp rendered as "[HH:mm:ss]" for the message-time label. - public string TimeText => Timestamp.ToString("[HH:mm:ss]"); + /// Timestamp as "[HH:mm:ss]", formatted identically on every machine regardless of culture. + public string TimeText => timeText ??= Timestamp.ToString(TimeFormat, CultureInfo.InvariantCulture); + + /// + /// "{source}: {content}", or just the source when there is no content. The same text is shown + /// in the viewer and written to the Unity log when a message is forwarded. + /// + public string Label => label ??= ComposeLabel(Source, Content); - /// Full "{source}: {content}" text used by both list rows and the details pane. - public string Label => $"{Source}: {Content}"; + internal static string ComposeLabel(string source, string content) + => string.IsNullOrEmpty(content) ? source : string.Concat(source, LabelSeparator, content); } } From 6e55d2698c84262afe9c953a9e0f68e2702b371d Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:16:05 +0300 Subject: [PATCH 05/42] fix: reentrant handlers --- UnityPackage/Runtime/ConsoleInstance.cs | 64 ++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index 6edea0c..a1266ea 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -34,7 +34,15 @@ public sealed class ConsoleInstance : IConsoleInstance // instead of holding on to capacity it is unlikely to need again. private const int ClearedCapacityTrimThreshold = 1024; + // How deeply handlers may log from inside other handlers on one thread before events stop + // being raised. Generous for legitimate chains, far below any stack limit. + private const int MaximumDispatchDepth = 8; + private static int _instanceCounter; + private static int _recursionReported; + + [ThreadStatic] + private static int _dispatchDepth; private readonly object _gate = new object(); private readonly List _messages = new List(); @@ -270,23 +278,34 @@ public void Dispose() #endif } + // Handlers are copied out of the events first, so a concurrent unsubscribe cannot turn an + // invocation into a null call. private void RaiseCreated(ConsoleMessageType type, ConsoleMessage message) { - Invoke(MessageCreated, message); + Action messageHandler = MessageCreated; + Action errorHandler = type == ConsoleMessageType.Error ? ErrorCreated : null; - if (type == ConsoleMessageType.Error) + if ((messageHandler == null && errorHandler == null) || !TryEnterDispatch()) + { + return; + } + + try { - Invoke(ErrorCreated, message); + Invoke(messageHandler, message); + Invoke(errorHandler, message); + } + finally + { + _dispatchDepth--; } } - // Mirrors Invoke below: the handler is copied out of the static event first, so a - // concurrent unsubscribe cannot turn the invocation into a null call. private static void RaiseCreated(IConsoleInstance instance) { Action handler = Created; - if (handler == null) + if (handler == null || !TryEnterDispatch()) { return; } @@ -300,6 +319,39 @@ private static void RaiseCreated(IConsoleInstance instance) // A faulty subscriber must never break the construction that triggered it. Debug.LogException(exception); } + finally + { + _dispatchDepth--; + } + } + + // A handler that logs into what it observes (or constructs an instance from Created) would + // recurse until the stack overflows, which no catch can stop and which takes the whole + // process down. Nesting is therefore capped per thread: deeper messages are still kept and + // forwarded, only their events are skipped. + private static bool TryEnterDispatch() + { + if (_dispatchDepth >= MaximumDispatchDepth) + { + ReportRecursion(); + return false; + } + + _dispatchDepth++; + return true; + } + + private static void ReportRecursion() + { + if (Interlocked.Exchange(ref _recursionReported, 1) != 0) + { + return; + } + + Debug.LogWarning( + $"ConsoleContainer: event handlers kept logging from inside other handlers more than {MaximumDispatchDepth} " + + "levels deep. Events for the deeper messages were skipped to prevent a stack overflow; the messages " + + "themselves are still kept. This is reported once per session."); } // The handler is copied into a parameter before it is called, so a From 95c126ccd181984f28cae62fb62abff648722f1c Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:16:59 +0300 Subject: [PATCH 06/42] refactor: stack capture --- UnityPackage/Runtime/CallstackCapture.cs | 153 ++++++++++++++++++ UnityPackage/Runtime/CallstackCapture.cs.meta | 2 + UnityPackage/Runtime/ConsoleInstance.cs | 68 +------- 3 files changed, 156 insertions(+), 67 deletions(-) create mode 100644 UnityPackage/Runtime/CallstackCapture.cs create mode 100644 UnityPackage/Runtime/CallstackCapture.cs.meta diff --git a/UnityPackage/Runtime/CallstackCapture.cs b/UnityPackage/Runtime/CallstackCapture.cs new file mode 100644 index 0000000..9517bfc --- /dev/null +++ b/UnityPackage/Runtime/CallstackCapture.cs @@ -0,0 +1,153 @@ +#if UNITY_EDITOR +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Reflection; + +namespace reromanlee.ConsoleContainer +{ + /// + /// Editor-only capture of source-resolvable call stacks for the Console Viewer. + /// + /// Messages logged from the same places repeat the same frames endlessly, so per-method + /// details and file paths are resolved once and shared: a retained message only pays for its + /// own frame array, never for another copy of the same strings. + /// + internal static class CallstackCapture + { + private const char GeneratedNameStart = '<'; + private const char GeneratedNameEnd = '>'; + private const string StateMachineMethod = "MoveNext"; + + private static readonly ConcurrentDictionary Methods = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary FilePaths = + new ConcurrentDictionary(StringComparer.Ordinal); + + // Cached delegate: a method group passed to GetOrAdd would allocate on every call. + private static readonly Func Describe = DescribeMethod; + + [ThreadStatic] + private static List _scratch; + + /// Captures the calling thread's stack, without the logging methods themselves. + internal static CallstackFrame[] FromCurrentThread() => Convert(new StackTrace(1, true).GetFrames()); + + private static CallstackFrame[] Convert(StackFrame[] frames) + { + if (frames == null || frames.Length == 0) + { + return Array.Empty(); + } + + List resolved = _scratch ??= new List(frames.Length); + resolved.Clear(); + + foreach (StackFrame frame in frames) + { + MethodBase method = frame.GetMethod(); + if (method == null) + { + continue; + } + + MethodDetails details = Methods.GetOrAdd(method, Describe); + if (details.IsHidden) + { + continue; + } + + string file = frame.GetFileName(); + int line = frame.GetFileLineNumber(); + if (string.IsNullOrEmpty(file) || line <= 0) + { + // Engine/native frame with no source info — can't open in an IDE. + continue; + } + + resolved.Add(new CallstackFrame(FilePaths.GetOrAdd(file, file), line, details.DisplayName)); + } + + CallstackFrame[] result = resolved.Count == 0 ? Array.Empty() : resolved.ToArray(); + resolved.Clear(); + return result; + } + + private static MethodDetails DescribeMethod(MethodBase method) + { + Type declaringType = method.DeclaringType; + + // Only the logging path itself is skipped, so the top frame is the caller's log site. + // Filtering by namespace would wrongly drop user code that lives under it (samples). + bool isHidden = declaringType == typeof(ConsoleInstance) + || declaringType == typeof(ConsoleInstanceExtensions) + || declaringType == typeof(CallstackCapture); + + return new MethodDetails(ResolveMethodName(declaringType, method), isHidden); + } + + // Compiler-generated frames read as the method they came from: an iterator or async state + // machine ("d__4.MoveNext") and a lambda ("<>c.b__0_0") both name their + // source method on the nearest type a developer actually wrote. + private static string ResolveMethodName(Type declaringType, MethodBase method) + { + string methodName = method.Name; + if (declaringType == null) + { + return methodName; + } + + if (TryExtractSourceName(methodName, out string lambdaOwner)) + { + methodName = lambdaOwner; + } + + Type type = declaringType; + while (type != null && type.Name.Length > 0 && type.Name[0] == GeneratedNameStart) + { + if (method.Name == StateMachineMethod && TryExtractSourceName(type.Name, out string stateMachineOwner)) + { + methodName = stateMachineOwner; + } + + type = type.DeclaringType; + } + + return string.Concat(SourceNames.Of(type ?? declaringType), ".", methodName); + } + + private static bool TryExtractSourceName(string generatedName, out string sourceName) + { + sourceName = null; + if (generatedName.Length < 3 || generatedName[0] != GeneratedNameStart) + { + return false; + } + + // "<>c" display classes carry no name between the brackets. + int end = generatedName.IndexOf(GeneratedNameEnd); + if (end <= 1) + { + return false; + } + + sourceName = generatedName.Substring(1, end - 1); + return true; + } + + private readonly struct MethodDetails + { + public readonly string DisplayName; + public readonly bool IsHidden; + + public MethodDetails(string displayName, bool isHidden) + { + DisplayName = displayName; + IsHidden = isHidden; + } + } + } +} +#endif diff --git a/UnityPackage/Runtime/CallstackCapture.cs.meta b/UnityPackage/Runtime/CallstackCapture.cs.meta new file mode 100644 index 0000000..a17e25b --- /dev/null +++ b/UnityPackage/Runtime/CallstackCapture.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 27b78a91799d670451c003263c0cb166 diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index a1266ea..b00d270 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -3,10 +3,6 @@ using System.Threading; using Debug = UnityEngine.Debug; -#if UNITY_EDITOR -using System.Diagnostics; -#endif - namespace reromanlee.ConsoleContainer { /// @@ -184,7 +180,7 @@ public void Create(ConsoleMessageType type, string source, string content) #if UNITY_EDITOR // The editor keeps every message for the viewer, so the entry is // always built. - ConsoleMessage message = new ConsoleMessage(type, source, content, CaptureCallstack()); + ConsoleMessage message = new ConsoleMessage(type, source, content, CallstackCapture.FromCurrentThread()); lock (_gate) { @@ -425,68 +421,6 @@ private bool HasMessages() return _messages.Count > 0; } } - - private static CallstackFrame[] CaptureCallstack() - { - StackFrame[] frames = new StackTrace(true).GetFrames(); - if (frames == null) - { - return Array.Empty(); - } - - List result = new List(frames.Length); - foreach (StackFrame frame in frames) - { - System.Reflection.MethodBase method = frame.GetMethod(); - Type declaringType = method?.DeclaringType; - - // Skip only the logging methods themselves so the top frame is - // the caller's real log site. Filtering by the package namespace - // would wrongly drop user code that lives under it (e.g. samples). - if (declaringType == typeof(ConsoleInstance) || declaringType == typeof(ConsoleInstanceExtensions)) - { - continue; - } - - string file = frame.GetFileName(); - int line = frame.GetFileLineNumber(); - if (string.IsNullOrEmpty(file) || line <= 0) - { - // Engine/native frame with no source info — can't open in an IDE. - continue; - } - - result.Add(new CallstackFrame(file, line, ResolveMethodName(declaringType, method))); - } - - return result.ToArray(); - } - - // Presents compiler-generated iterator/async frames ("d__N.MoveNext") - // using their original source method name. - private static string ResolveMethodName(Type declaringType, System.Reflection.MethodBase method) - { - if (declaringType == null) - { - return method?.Name; - } - - string typeName = declaringType.Name; - string methodName = method?.Name; - - if (typeName.Length > 0 && typeName[0] == '<') - { - int end = typeName.IndexOf('>'); - if (end > 1) - { - methodName = typeName.Substring(1, end - 1); - Type outer = declaringType.DeclaringType; - typeName = outer != null ? outer.Name : typeName; - } - } - - return $"{typeName}.{methodName}"; - } #else // Cheap pre-check that keeps a build from allocating a ConsoleMessage // nobody would receive. From 7afac649556b1c76f8c8de2819360a0f86aabc7a Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:17:26 +0300 Subject: [PATCH 07/42] feature: hidden frames --- UnityPackage/Runtime/CallstackCapture.cs | 12 ++++++++---- UnityPackage/Runtime/ConsoleInstance.cs | 4 +++- UnityPackage/Runtime/ConsoleInstanceExtensions.cs | 9 +++++++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/UnityPackage/Runtime/CallstackCapture.cs b/UnityPackage/Runtime/CallstackCapture.cs index 9517bfc..d64bda0 100644 --- a/UnityPackage/Runtime/CallstackCapture.cs +++ b/UnityPackage/Runtime/CallstackCapture.cs @@ -12,7 +12,8 @@ namespace reromanlee.ConsoleContainer /// /// Messages logged from the same places repeat the same frames endlessly, so per-method /// details and file paths are resolved once and shared: a retained message only pays for its - /// own frame array, never for another copy of the same strings. + /// own frame array, never for another copy of the same strings. The attribute lookup that + /// decides whether a frame is hidden runs once per method for the same reason. /// internal static class CallstackCapture { @@ -79,11 +80,14 @@ private static MethodDetails DescribeMethod(MethodBase method) { Type declaringType = method.DeclaringType; - // Only the logging path itself is skipped, so the top frame is the caller's log site. - // Filtering by namespace would wrongly drop user code that lives under it (samples). + // The logging path itself is skipped, so the top frame is the caller's log site, and so is + // anything marked [HideInCallstack] — the same attribute the Unity Console honours — which + // lets a project's own logging wrappers drop out too. Filtering by namespace instead would + // wrongly drop user code that lives under it (samples). bool isHidden = declaringType == typeof(ConsoleInstance) || declaringType == typeof(ConsoleInstanceExtensions) - || declaringType == typeof(CallstackCapture); + || declaringType == typeof(CallstackCapture) + || method.IsDefined(typeof(UnityEngine.HideInCallstackAttribute), false); return new MethodDetails(ResolveMethodName(declaringType, method), isHidden); } diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index b00d270..412ea0a 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using System.Threading; -using Debug = UnityEngine.Debug; +using UnityEngine; namespace reromanlee.ConsoleContainer { @@ -167,6 +167,7 @@ public bool IsEnabled(ConsoleMessageType type) /// Severity of the message. /// Name of whatever produced the message; "null" when empty. /// Message body. + [HideInCallstack] public void Create(ConsoleMessageType type, string source, string content) { if (IsDisposed) @@ -373,6 +374,7 @@ private static void Invoke(Action handler, ConsoleMessage messag } } + [HideInCallstack] private static void ForwardToUnityConsole(ConsoleMessageType type, string label) { switch (type) diff --git a/UnityPackage/Runtime/ConsoleInstanceExtensions.cs b/UnityPackage/Runtime/ConsoleInstanceExtensions.cs index f2b8310..b797092 100644 --- a/UnityPackage/Runtime/ConsoleInstanceExtensions.cs +++ b/UnityPackage/Runtime/ConsoleInstanceExtensions.cs @@ -1,4 +1,5 @@ using System; +using UnityEngine; namespace reromanlee.ConsoleContainer { @@ -14,24 +15,31 @@ public static class ConsoleInstanceExtensions { private const string ContentSeparator = " "; + [HideInCallstack] public static void CreateText(this IConsoleInstance console, object source, string message) => CreateSingle(console, ConsoleMessageType.Text, source, message); + [HideInCallstack] public static void CreateText(this IConsoleInstance console, object source, params string[] messageContent) => CreateJoined(console, ConsoleMessageType.Text, source, messageContent); + [HideInCallstack] public static void CreateWarning(this IConsoleInstance console, object source, string message) => CreateSingle(console, ConsoleMessageType.Warning, source, message); + [HideInCallstack] public static void CreateWarning(this IConsoleInstance console, object source, params string[] messageContent) => CreateJoined(console, ConsoleMessageType.Warning, source, messageContent); + [HideInCallstack] public static void CreateError(this IConsoleInstance console, object source, string message) => CreateSingle(console, ConsoleMessageType.Error, source, message); + [HideInCallstack] public static void CreateError(this IConsoleInstance console, object source, params string[] messageContent) => CreateJoined(console, ConsoleMessageType.Error, source, messageContent); + [HideInCallstack] private static void CreateSingle(IConsoleInstance console, ConsoleMessageType type, object source, string message) { if (console == null) @@ -45,6 +53,7 @@ private static void CreateSingle(IConsoleInstance console, ConsoleMessageType ty } } + [HideInCallstack] private static void CreateJoined(IConsoleInstance console, ConsoleMessageType type, object source, string[] messageContent) { if (console == null) From 5733a707f3aa1d76990cbdcf46ecadd796b5073b Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:18:40 +0300 Subject: [PATCH 08/42] feature: log exceptions --- UnityPackage/Runtime/CallstackCapture.cs | 62 ++++++++++++++++--- UnityPackage/Runtime/ConsoleInstance.cs | 27 ++++++-- .../Runtime/ConsoleInstanceExtensions.cs | 27 ++++++++ UnityPackage/Runtime/ConsoleMessage.cs | 14 ++++- UnityPackage/Runtime/IConsoleInstance.cs | 3 +- 5 files changed, 115 insertions(+), 18 deletions(-) diff --git a/UnityPackage/Runtime/CallstackCapture.cs b/UnityPackage/Runtime/CallstackCapture.cs index d64bda0..32870af 100644 --- a/UnityPackage/Runtime/CallstackCapture.cs +++ b/UnityPackage/Runtime/CallstackCapture.cs @@ -21,6 +21,9 @@ internal static class CallstackCapture private const char GeneratedNameEnd = '>'; private const string StateMachineMethod = "MoveNext"; + // Bounds the inner-exception walk, which also guards against a pathological cycle. + private const int MaximumExceptionDepth = 16; + private static readonly ConcurrentDictionary Methods = new ConcurrentDictionary(); @@ -34,17 +37,62 @@ internal static class CallstackCapture private static List _scratch; /// Captures the calling thread's stack, without the logging methods themselves. - internal static CallstackFrame[] FromCurrentThread() => Convert(new StackTrace(1, true).GetFrames()); + internal static CallstackFrame[] FromCurrentThread() + { + List resolved = BeginCapture(); + Append(new StackTrace(1, true).GetFrames(), resolved); + return EndCapture(resolved); + } - private static CallstackFrame[] Convert(StackFrame[] frames) + /// + /// Captures where was thrown, innermost exception first, so the + /// top frame is the original throw site — the order .NET itself prints them in. An exception + /// that was never thrown carries no stack, and falls back to the logging site instead. + /// + internal static CallstackFrame[] FromException(Exception exception) { - if (frames == null || frames.Length == 0) + List resolved = BeginCapture(); + + Exception[] chain = new Exception[MaximumExceptionDepth]; + int depth = 0; + for (Exception current = exception; current != null && depth < chain.Length; current = current.InnerException) + { + chain[depth++] = current; + } + + for (int i = depth - 1; i >= 0; i--) { - return Array.Empty(); + Append(new StackTrace(chain[i], true).GetFrames(), resolved); } - List resolved = _scratch ??= new List(frames.Length); + if (resolved.Count == 0) + { + Append(new StackTrace(1, true).GetFrames(), resolved); + } + + return EndCapture(resolved); + } + + private static List BeginCapture() + { + List resolved = _scratch ??= new List(32); + resolved.Clear(); + return resolved; + } + + private static CallstackFrame[] EndCapture(List resolved) + { + CallstackFrame[] result = resolved.Count == 0 ? Array.Empty() : resolved.ToArray(); resolved.Clear(); + return result; + } + + private static void Append(StackFrame[] frames, List resolved) + { + if (frames == null) + { + return; + } foreach (StackFrame frame in frames) { @@ -70,10 +118,6 @@ private static CallstackFrame[] Convert(StackFrame[] frames) resolved.Add(new CallstackFrame(FilePaths.GetOrAdd(file, file), line, details.DisplayName)); } - - CallstackFrame[] result = resolved.Count == 0 ? Array.Empty() : resolved.ToArray(); - resolved.Clear(); - return result; } private static MethodDetails DescribeMethod(MethodBase method) diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index 412ea0a..33fa708 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -167,8 +167,13 @@ public bool IsEnabled(ConsoleMessageType type) /// Severity of the message. /// Name of whatever produced the message; "null" when empty. /// Message body. + /// + /// Exception the message reports, if any. Its stack trace replaces the logging site's, and a + /// forwarded error goes through so crash reporters + /// hooked into the Unity log see a real exception. + /// [HideInCallstack] - public void Create(ConsoleMessageType type, string source, string content) + public void Create(ConsoleMessageType type, string source, string content, Exception exception = null) { if (IsDisposed) { @@ -181,7 +186,11 @@ public void Create(ConsoleMessageType type, string source, string content) #if UNITY_EDITOR // The editor keeps every message for the viewer, so the entry is // always built. - ConsoleMessage message = new ConsoleMessage(type, source, content, CallstackCapture.FromCurrentThread()); + CallstackFrame[] callstack = exception != null + ? CallstackCapture.FromException(exception) + : CallstackCapture.FromCurrentThread(); + + ConsoleMessage message = new ConsoleMessage(type, source, content, exception, callstack); lock (_gate) { @@ -192,21 +201,21 @@ public void Create(ConsoleMessageType type, string source, string content) if (UnityConsoleForwarding.ShouldForward(type)) { - ForwardToUnityConsole(type, message.Label); + ForwardToUnityConsole(type, message.Label, exception); } RaiseCreated(type, message); #else if (UnityConsoleForwarding.ShouldForward(type)) { - ForwardToUnityConsole(type, ConsoleMessage.ComposeLabel(source, content)); + ForwardToUnityConsole(type, ConsoleMessage.ComposeLabel(source, content), exception); } // Player builds keep no history, so the entry is only worth // allocating when something is actually listening for it. if (HasListener(type)) { - RaiseCreated(type, new ConsoleMessage(type, source, content, null)); + RaiseCreated(type, new ConsoleMessage(type, source, content, exception, null)); } #endif } @@ -375,8 +384,14 @@ private static void Invoke(Action handler, ConsoleMessage messag } [HideInCallstack] - private static void ForwardToUnityConsole(ConsoleMessageType type, string label) + private static void ForwardToUnityConsole(ConsoleMessageType type, string label, Exception exception) { + if (exception != null && type == ConsoleMessageType.Error) + { + Debug.LogException(exception); + return; + } + switch (type) { case ConsoleMessageType.Text: diff --git a/UnityPackage/Runtime/ConsoleInstanceExtensions.cs b/UnityPackage/Runtime/ConsoleInstanceExtensions.cs index b797092..f4a4766 100644 --- a/UnityPackage/Runtime/ConsoleInstanceExtensions.cs +++ b/UnityPackage/Runtime/ConsoleInstanceExtensions.cs @@ -14,6 +14,8 @@ namespace reromanlee.ConsoleContainer public static class ConsoleInstanceExtensions { private const string ContentSeparator = " "; + private const string ExceptionSeparator = ": "; + private const string MissingException = "Exception: null"; [HideInCallstack] public static void CreateText(this IConsoleInstance console, object source, string message) @@ -39,6 +41,31 @@ public static void CreateError(this IConsoleInstance console, object source, str public static void CreateError(this IConsoleInstance console, object source, params string[] messageContent) => CreateJoined(console, ConsoleMessageType.Error, source, messageContent); + /// + /// Creates an that reports : + /// its content reads "{ExceptionType}: {Message}", its call stack is where the exception was + /// thrown, and hands the original object to handlers. + /// + [HideInCallstack] + public static void CreateException(this IConsoleInstance console, object source, Exception exception) + { + if (console == null) + { + throw new ArgumentNullException(nameof(console)); + } + + if (!console.IsEnabled(ConsoleMessageType.Error)) + { + return; + } + + string content = exception == null + ? MissingException + : string.Concat(SourceNames.Of(exception.GetType()), ExceptionSeparator, exception.Message); + + console.Create(ConsoleMessageType.Error, SourceNames.Resolve(source), content, exception); + } + [HideInCallstack] private static void CreateSingle(IConsoleInstance console, ConsoleMessageType type, object source, string message) { diff --git a/UnityPackage/Runtime/ConsoleMessage.cs b/UnityPackage/Runtime/ConsoleMessage.cs index f5c11c0..097322c 100644 --- a/UnityPackage/Runtime/ConsoleMessage.cs +++ b/UnityPackage/Runtime/ConsoleMessage.cs @@ -42,16 +42,26 @@ public sealed class ConsoleMessage /// The message body (all content arguments joined by single spaces). public string Content { get; } - /// Source-resolvable call stack, innermost caller first. Empty in player builds. + /// + /// Source-resolvable call stack, innermost caller first — the exception's own stack when + /// is set. Empty in player builds. + /// public IReadOnlyList Callstack { get; } - internal ConsoleMessage(ConsoleMessageType type, string source, string content, IReadOnlyList callstack) + /// + /// The exception this message reports, or null. Handed to handlers as is, so crash reporters + /// receive the original object; in the editor it stays referenced while the message is kept. + /// + public Exception Exception { get; } + + internal ConsoleMessage(ConsoleMessageType type, string source, string content, Exception exception, IReadOnlyList callstack) { Timestamp = DateTime.Now; Sequence = Interlocked.Increment(ref _globalSequence); Type = type; Source = source ?? string.Empty; Content = content ?? string.Empty; + Exception = exception; Callstack = callstack ?? Array.Empty(); } diff --git a/UnityPackage/Runtime/IConsoleInstance.cs b/UnityPackage/Runtime/IConsoleInstance.cs index 2ba207a..4a5627c 100644 --- a/UnityPackage/Runtime/IConsoleInstance.cs +++ b/UnityPackage/Runtime/IConsoleInstance.cs @@ -43,7 +43,8 @@ public interface IConsoleInstance : IDisposable /// Severity of the message. /// Name of whatever produced the message. /// Message body. - void Create(ConsoleMessageType type, string source, string content); + /// Exception the message reports, if any; its stack trace replaces the logging site's. + void Create(ConsoleMessageType type, string source, string content, Exception exception = null); /// Removes every message this instance holds. void Clear(); From a7aa83b38d9968d922fa9b02dff4de14b6eb5db0 Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:19:13 +0300 Subject: [PATCH 09/42] feature: capture toggles --- .../Runtime/ConsoleContainerSettings.cs | 24 +++++++++++++ UnityPackage/Runtime/ConsoleInstance.cs | 4 ++- UnityPackage/Runtime/EditorHistoryPolicy.cs | 34 +++++++++++++++++++ .../Runtime/EditorHistoryPolicy.cs.meta | 2 ++ 4 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 UnityPackage/Runtime/EditorHistoryPolicy.cs create mode 100644 UnityPackage/Runtime/EditorHistoryPolicy.cs.meta diff --git a/UnityPackage/Runtime/ConsoleContainerSettings.cs b/UnityPackage/Runtime/ConsoleContainerSettings.cs index 5d60815..3c1d017 100644 --- a/UnityPackage/Runtime/ConsoleContainerSettings.cs +++ b/UnityPackage/Runtime/ConsoleContainerSettings.cs @@ -29,6 +29,9 @@ public sealed class ConsoleContainerSettings : ScriptableObject /// Per-type editor forwarding used when no settings asset exists. internal const bool DefaultLogInEditor = true; + /// Per-type editor call stack capture used when no settings asset exists. + internal const bool DefaultCaptureCallstack = true; + [Header("Player build logging")] [Tooltip("Forward Text messages to Debug.Log in player builds.")] [SerializeField] private bool logTextInBuild = true; @@ -55,6 +58,18 @@ public sealed class ConsoleContainerSettings : ScriptableObject "declared with LogAssert.Expect.")] [SerializeField] private bool logErrorsInEditor = DefaultLogInEditor; + [Header("Editor history")] + [Tooltip("Capture a clickable call stack for Text messages in the editor. Stack capture is by far " + + "the most expensive part of a log call; turn it off for messages logged on hot paths.")] + [SerializeField] private bool captureTextCallstack = DefaultCaptureCallstack; + + [Tooltip("Capture a clickable call stack for Warning messages in the editor.")] + [SerializeField] private bool captureWarningCallstack = DefaultCaptureCallstack; + + [Tooltip("Capture a clickable call stack for Error messages in the editor. " + + "Messages that report an exception always show where it was thrown.")] + [SerializeField] private bool captureErrorCallstack = DefaultCaptureCallstack; + public bool LogTextInBuild => logTextInBuild; public bool LogWarningsInBuild => logWarningsInBuild; public bool LogErrorsInBuild => logErrorsInBuild; @@ -66,6 +81,15 @@ public sealed class ConsoleContainerSettings : ScriptableObject public bool LogWarningsInEditor => logWarningsInEditor; public bool LogErrorsInEditor => logErrorsInEditor; + /// Whether Text messages capture a call stack in the editor. + public bool CaptureTextCallstack => captureTextCallstack; + + /// Whether Warning messages capture a call stack in the editor. + public bool CaptureWarningCallstack => captureWarningCallstack; + + /// Whether Error messages capture a call stack in the editor. + public bool CaptureErrorCallstack => captureErrorCallstack; + private static volatile ConsoleContainerSettings _active; private static volatile bool _loaded; private static volatile int _mainThreadIdentifier; diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index 33fa708..598757b 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -188,7 +188,9 @@ public void Create(ConsoleMessageType type, string source, string content, Excep // always built. CallstackFrame[] callstack = exception != null ? CallstackCapture.FromException(exception) - : CallstackCapture.FromCurrentThread(); + : EditorHistoryPolicy.ShouldCaptureCallstack(type) + ? CallstackCapture.FromCurrentThread() + : Array.Empty(); ConsoleMessage message = new ConsoleMessage(type, source, content, exception, callstack); diff --git a/UnityPackage/Runtime/EditorHistoryPolicy.cs b/UnityPackage/Runtime/EditorHistoryPolicy.cs new file mode 100644 index 0000000..fbc49f7 --- /dev/null +++ b/UnityPackage/Runtime/EditorHistoryPolicy.cs @@ -0,0 +1,34 @@ +#if UNITY_EDITOR +namespace reromanlee.ConsoleContainer +{ + /// + /// Single place that answers how much detail the editor keeps for each message, read from the + /// active or the package defaults when there is none. + /// Safe to call from any thread. + /// + internal static class EditorHistoryPolicy + { + /// Whether a message of records the call stack that logged it. + internal static bool ShouldCaptureCallstack(ConsoleMessageType type) + { + ConsoleContainerSettings settings = ConsoleContainerSettings.Active; + if (settings == null) + { + return ConsoleContainerSettings.DefaultCaptureCallstack; + } + + switch (type) + { + case ConsoleMessageType.Text: + return settings.CaptureTextCallstack; + case ConsoleMessageType.Warning: + return settings.CaptureWarningCallstack; + case ConsoleMessageType.Error: + return settings.CaptureErrorCallstack; + default: + return false; + } + } + } +} +#endif diff --git a/UnityPackage/Runtime/EditorHistoryPolicy.cs.meta b/UnityPackage/Runtime/EditorHistoryPolicy.cs.meta new file mode 100644 index 0000000..b11dc29 --- /dev/null +++ b/UnityPackage/Runtime/EditorHistoryPolicy.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ecdeb5c5e3a8c90c09214b6a1df5320a From 49e98ad452b37d29baa349d1856d353fc8e2bb5b Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:20:31 +0300 Subject: [PATCH 10/42] feature: retention limit --- .../Runtime/ConsoleContainerSettings.cs | 11 ++ UnityPackage/Runtime/ConsoleInstance.cs | 34 ++--- UnityPackage/Runtime/EditorHistoryPolicy.cs | 21 ++- UnityPackage/Runtime/MessageBuffer.cs | 131 ++++++++++++++++++ UnityPackage/Runtime/MessageBuffer.cs.meta | 2 + 5 files changed, 177 insertions(+), 22 deletions(-) create mode 100644 UnityPackage/Runtime/MessageBuffer.cs create mode 100644 UnityPackage/Runtime/MessageBuffer.cs.meta diff --git a/UnityPackage/Runtime/ConsoleContainerSettings.cs b/UnityPackage/Runtime/ConsoleContainerSettings.cs index 3c1d017..64c7331 100644 --- a/UnityPackage/Runtime/ConsoleContainerSettings.cs +++ b/UnityPackage/Runtime/ConsoleContainerSettings.cs @@ -32,6 +32,9 @@ public sealed class ConsoleContainerSettings : ScriptableObject /// Per-type editor call stack capture used when no settings asset exists. internal const bool DefaultCaptureCallstack = true; + /// Most messages each instance keeps in the editor when no settings asset exists. + internal const int DefaultMaxMessagesPerInstance = 10000; + [Header("Player build logging")] [Tooltip("Forward Text messages to Debug.Log in player builds.")] [SerializeField] private bool logTextInBuild = true; @@ -59,6 +62,11 @@ public sealed class ConsoleContainerSettings : ScriptableObject [SerializeField] private bool logErrorsInEditor = DefaultLogInEditor; [Header("Editor history")] + [Tooltip("Most messages each instance keeps in the editor; once reached, the oldest are dropped " + + "first. Bounds memory in long sessions. 0 keeps everything.")] + [Min(0)] + [SerializeField] private int maxMessagesPerInstance = DefaultMaxMessagesPerInstance; + [Tooltip("Capture a clickable call stack for Text messages in the editor. Stack capture is by far " + "the most expensive part of a log call; turn it off for messages logged on hot paths.")] [SerializeField] private bool captureTextCallstack = DefaultCaptureCallstack; @@ -81,6 +89,9 @@ public sealed class ConsoleContainerSettings : ScriptableObject public bool LogWarningsInEditor => logWarningsInEditor; public bool LogErrorsInEditor => logErrorsInEditor; + /// Most messages each instance keeps in the editor before dropping the oldest; 0 keeps everything. + public int MaxMessagesPerInstance => maxMessagesPerInstance; + /// Whether Text messages capture a call stack in the editor. public bool CaptureTextCallstack => captureTextCallstack; diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index 598757b..b05ee8d 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -26,10 +26,6 @@ public sealed class ConsoleInstance : IConsoleInstance { private const string MissingSource = "null"; - // Above this many entries, a cleared instance releases its backing array - // instead of holding on to capacity it is unlikely to need again. - private const int ClearedCapacityTrimThreshold = 1024; - // How deeply handlers may log from inside other handlers on one thread before events stop // being raised. Generous for legitimate chains, far below any stack limit. private const int MaximumDispatchDepth = 8; @@ -40,8 +36,10 @@ public sealed class ConsoleInstance : IConsoleInstance [ThreadStatic] private static int _dispatchDepth; +#if UNITY_EDITOR private readonly object _gate = new object(); - private readonly List _messages = new List(); + private readonly MessageBuffer _history = new MessageBuffer(); +#endif private int _disposed; @@ -194,9 +192,10 @@ public void Create(ConsoleMessageType type, string source, string content, Excep ConsoleMessage message = new ConsoleMessage(type, source, content, exception, callstack); + int limit = EditorHistoryPolicy.MessageLimit; lock (_gate) { - _messages.Add(message); + _history.Add(message, limit); } ConsoleRegistry.NotifyMessageAdded(this); @@ -225,21 +224,17 @@ public void Create(ConsoleMessageType type, string source, string content, Excep /// /// Removes every message from this instance. Clearing an already disposed /// instance also drops it from the viewer, since nothing is left to - /// inspect and a stale entry would only crowd the dropdown. + /// inspect and a stale entry would only crowd the dropdown. Player builds + /// keep no history, so there it does nothing. /// public void Clear() { +#if UNITY_EDITOR lock (_gate) { - _messages.Clear(); - - if (_messages.Capacity > ClearedCapacityTrimThreshold) - { - _messages.Capacity = 0; - } + _history.Clear(); } -#if UNITY_EDITOR if (IsDisposed) { ConsoleRegistry.Unregister(this); @@ -419,16 +414,17 @@ internal void CollectMessagesAfter(long afterSequence, List buff { lock (_gate) { - // _messages is append-only and therefore already sorted ascending + // History is kept oldest first and therefore sorted ascending // by Sequence, so the new messages are a contiguous suffix. - for (int i = _messages.Count - 1; i >= 0; i--) + for (int i = _history.Count - 1; i >= 0; i--) { - if (_messages[i].Sequence <= afterSequence) + ConsoleMessage message = _history[i]; + if (message.Sequence <= afterSequence) { break; } - buffer.Add(_messages[i]); + buffer.Add(message); } } } @@ -437,7 +433,7 @@ private bool HasMessages() { lock (_gate) { - return _messages.Count > 0; + return _history.Count > 0; } } #else diff --git a/UnityPackage/Runtime/EditorHistoryPolicy.cs b/UnityPackage/Runtime/EditorHistoryPolicy.cs index fbc49f7..51a7050 100644 --- a/UnityPackage/Runtime/EditorHistoryPolicy.cs +++ b/UnityPackage/Runtime/EditorHistoryPolicy.cs @@ -1,13 +1,28 @@ #if UNITY_EDITOR +using System; + namespace reromanlee.ConsoleContainer { /// - /// Single place that answers how much detail the editor keeps for each message, read from the - /// active or the package defaults when there is none. - /// Safe to call from any thread. + /// Single place that answers how much history the editor keeps — how many messages per instance, + /// and whether each records its call stack — read from the active + /// , or the package defaults when there is none. Safe to call + /// from any thread. /// internal static class EditorHistoryPolicy { + /// Most messages each instance keeps before dropping the oldest; zero means unlimited. + internal static int MessageLimit + { + get + { + ConsoleContainerSettings settings = ConsoleContainerSettings.Active; + return settings != null + ? Math.Max(0, settings.MaxMessagesPerInstance) + : ConsoleContainerSettings.DefaultMaxMessagesPerInstance; + } + } + /// Whether a message of records the call stack that logged it. internal static bool ShouldCaptureCallstack(ConsoleMessageType type) { diff --git a/UnityPackage/Runtime/MessageBuffer.cs b/UnityPackage/Runtime/MessageBuffer.cs new file mode 100644 index 0000000..174d967 --- /dev/null +++ b/UnityPackage/Runtime/MessageBuffer.cs @@ -0,0 +1,131 @@ +#if UNITY_EDITOR +using System; +using System.Collections.Generic; + +namespace reromanlee.ConsoleContainer +{ + /// + /// Growable ring buffer of messages with an optional size limit: once full, each new message + /// replaces the oldest one. + /// + /// Every message ever added owns a position in one ever-increasing cursor space, so a reader + /// that remembers where it stopped resumes exactly there — it never misses or repeats an + /// entry, however many were added or dropped in between, and clearing never rewinds it. + /// + /// Not thread-safe; the owning instance serializes access. + /// + internal sealed class MessageBuffer + { + private const int MinimumCapacity = 16; + + // Above this many slots, a cleared buffer releases its storage instead of holding on to + // capacity it is unlikely to need again. + private const int ClearedCapacityTrimThreshold = 1024; + + // Largest array the runtime allows; an unlimited buffer stops growing here and starts + // replacing its oldest entries like a limited one. + private const int MaximumCapacity = 0x7FFFFFC7; + + private ConsoleMessage[] items = Array.Empty(); + private int head; + private int count; + private long endPosition; + + /// Number of messages currently held. + internal int Count => count; + + /// Cursor of the oldest message still held. + internal long StartPosition => endPosition - count; + + /// Cursor just past the newest message; where a reader that is up to date resumes. + internal long EndPosition => endPosition; + + /// The held message at , oldest first. + internal ConsoleMessage this[int index] => items[Wrap(head + index)]; + + /// Appends a message, dropping the oldest ones first to stay within the limit. + /// Message to append. + /// Most messages to hold; zero or less means unlimited. + internal void Add(ConsoleMessage message, int limit) + { + int effectiveLimit = limit > 0 ? limit : MaximumCapacity; + + // A loop rather than a single removal, so lowering the limit takes effect at once. + while (count >= effectiveLimit) + { + RemoveOldest(); + } + + if (count == items.Length) + { + Grow(effectiveLimit); + } + + items[Wrap(head + count)] = message; + count++; + endPosition++; + } + + /// + /// Appends every message from onwards to + /// — or from the oldest still held, when the ones in between + /// were dropped — and returns the cursor to resume from next time. + /// + internal long CopySince(long cursor, List destination) + { + long start = StartPosition; + if (cursor < start) + { + cursor = start; + } + + for (long position = cursor; position < endPosition; position++) + { + destination.Add(items[Wrap(head + (int)(position - start))]); + } + + return endPosition; + } + + /// Drops every message. Positions keep counting, so existing cursors stay valid. + internal void Clear() + { + if (items.Length > ClearedCapacityTrimThreshold) + { + items = Array.Empty(); + } + else + { + Array.Clear(items, 0, items.Length); + } + + head = 0; + count = 0; + } + + private void RemoveOldest() + { + items[head] = null; + head = Wrap(head + 1); + count--; + } + + private void Grow(int limit) + { + long doubled = Math.Max(MinimumCapacity, (long)items.Length * 2); + ConsoleMessage[] grown = new ConsoleMessage[(int)Math.Min(doubled, limit)]; + + for (int i = 0; i < count; i++) + { + grown[i] = items[Wrap(head + i)]; + } + + items = grown; + head = 0; + } + + // head and any offset are each below the capacity, so one subtraction always wraps. + private int Wrap(int index) => index >= items.Length ? index - items.Length : index; + } +} +#endif diff --git a/UnityPackage/Runtime/MessageBuffer.cs.meta b/UnityPackage/Runtime/MessageBuffer.cs.meta new file mode 100644 index 0000000..d1ec0cd --- /dev/null +++ b/UnityPackage/Runtime/MessageBuffer.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e6fb9677b01447c9a1d902cc2d0d5442 From f2f621f26af1d7629b614ec7b1f612eda1a8e69d Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:20:46 +0300 Subject: [PATCH 11/42] fix: per-instance order --- UnityPackage/Runtime/ConsoleInstance.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index b05ee8d..e7dfdb3 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -190,11 +190,14 @@ public void Create(ConsoleMessageType type, string source, string content, Excep ? CallstackCapture.FromCurrentThread() : Array.Empty(); - ConsoleMessage message = new ConsoleMessage(type, source, content, exception, callstack); - int limit = EditorHistoryPolicy.MessageLimit; + ConsoleMessage message; + + // Built under the lock so sequence numbers are handed out in the order messages enter + // the history; threads logging concurrently could otherwise store them out of order. lock (_gate) { + message = new ConsoleMessage(type, source, content, exception, callstack); _history.Add(message, limit); } From 0771c55263216d093b1d44a14a239900ed63788a Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:22:36 +0300 Subject: [PATCH 12/42] feature: runtime settings --- .../Runtime/ConsoleContainerSettings.cs | 127 ++++++++++++++---- 1 file changed, 99 insertions(+), 28 deletions(-) diff --git a/UnityPackage/Runtime/ConsoleContainerSettings.cs b/UnityPackage/Runtime/ConsoleContainerSettings.cs index 64c7331..062875a 100644 --- a/UnityPackage/Runtime/ConsoleContainerSettings.cs +++ b/UnityPackage/Runtime/ConsoleContainerSettings.cs @@ -12,10 +12,12 @@ namespace reromanlee.ConsoleContainer /// window (see ); it is limited to test /// runs by default so the Unity Console stays clean during normal work. /// - /// To take effect in a build, create one asset (Assets ▸ Create ▸ - /// ConsoleContainer ▸ Settings) and place it inside any Resources - /// folder. When no asset exists, all messages are hidden in builds and the - /// editor defaults below apply. + /// To take effect in a build, create one asset from + /// Project Settings ▸ Console Container (or Assets ▸ Create ▸ + /// ConsoleContainer ▸ Settings, placed directly inside any Resources + /// folder). When no asset exists, all messages are hidden in builds and the + /// editor defaults below apply. also accepts a settings + /// object created at runtime, which overrides the asset. /// [CreateAssetMenu(fileName = ResourcesPath, menuName = "ConsoleContainer/Settings", order = 0)] public sealed class ConsoleContainerSettings : ScriptableObject @@ -78,48 +80,114 @@ public sealed class ConsoleContainerSettings : ScriptableObject "Messages that report an exception always show where it was thrown.")] [SerializeField] private bool captureErrorCallstack = DefaultCaptureCallstack; - public bool LogTextInBuild => logTextInBuild; - public bool LogWarningsInBuild => logWarningsInBuild; - public bool LogErrorsInBuild => logErrorsInBuild; + /// Whether Text messages are forwarded to Debug.Log in player builds. + public bool LogTextInBuild + { + get => logTextInBuild; + set => logTextInBuild = value; + } + + /// Whether Warning messages are forwarded to Debug.LogWarning in player builds. + public bool LogWarningsInBuild + { + get => logWarningsInBuild; + set => logWarningsInBuild = value; + } + + /// Whether Error messages are forwarded to Debug.LogError in player builds. + public bool LogErrorsInBuild + { + get => logErrorsInBuild; + set => logErrorsInBuild = value; + } /// When editor messages are mirrored into the Unity console. - public EditorForwardingMode EditorForwarding => editorForwarding; + public EditorForwardingMode EditorForwarding + { + get => editorForwarding; + set => editorForwarding = value; + } + + /// Whether Text messages are forwarded while editor forwarding is active. + public bool LogTextInEditor + { + get => logTextInEditor; + set => logTextInEditor = value; + } - public bool LogTextInEditor => logTextInEditor; - public bool LogWarningsInEditor => logWarningsInEditor; - public bool LogErrorsInEditor => logErrorsInEditor; + /// Whether Warning messages are forwarded while editor forwarding is active. + public bool LogWarningsInEditor + { + get => logWarningsInEditor; + set => logWarningsInEditor = value; + } + + /// Whether Error messages are forwarded while editor forwarding is active. + public bool LogErrorsInEditor + { + get => logErrorsInEditor; + set => logErrorsInEditor = value; + } /// Most messages each instance keeps in the editor before dropping the oldest; 0 keeps everything. - public int MaxMessagesPerInstance => maxMessagesPerInstance; + public int MaxMessagesPerInstance + { + get => maxMessagesPerInstance; + set => maxMessagesPerInstance = Math.Max(0, value); + } /// Whether Text messages capture a call stack in the editor. - public bool CaptureTextCallstack => captureTextCallstack; + public bool CaptureTextCallstack + { + get => captureTextCallstack; + set => captureTextCallstack = value; + } /// Whether Warning messages capture a call stack in the editor. - public bool CaptureWarningCallstack => captureWarningCallstack; + public bool CaptureWarningCallstack + { + get => captureWarningCallstack; + set => captureWarningCallstack = value; + } /// Whether Error messages capture a call stack in the editor. - public bool CaptureErrorCallstack => captureErrorCallstack; + public bool CaptureErrorCallstack + { + get => captureErrorCallstack; + set => captureErrorCallstack = value; + } - private static volatile ConsoleContainerSettings _active; + private static volatile ConsoleContainerSettings _asset; + private static volatile ConsoleContainerSettings _override; private static volatile bool _loaded; private static volatile int _mainThreadIdentifier; /// - /// The active settings asset loaded from Resources, or null - /// when none exists (package defaults then apply). The lookup is cached - /// after the first access. + /// The settings in effect: a runtime override when one is installed, otherwise the asset + /// loaded from Resources, or null when neither exists (package defaults then + /// apply). /// - /// is a main-thread-only API, so the lookup only - /// ever runs on the main thread; anywhere else this returns the last - /// resolved value rather than risking an exception. Because the cache is - /// warmed at startup, that only matters for a background thread logging - /// before the very first load. + /// Assign a settings object created at runtime (ScriptableObject.CreateInstance) to + /// change behaviour from code — a QA menu turning build logging on, a test silencing + /// forwarding — without touching the project asset, whose properties would persist to disk + /// if changed in the editor. Assign null to return to the asset. An override lasts + /// until it is replaced, destroyed, or play mode starts again. + /// + /// Safe to read from any thread. is a main-thread-only API, so the + /// asset lookup only ever runs there; anywhere else this returns the last resolved asset — + /// warmed at startup — rather than risking an exception. /// public static ConsoleContainerSettings Active { get { + // Unity's null check, so a destroyed override falls back to the asset. + ConsoleContainerSettings runtimeOverride = _override; + if (runtimeOverride != null) + { + return runtimeOverride; + } + if (!_loaded && Environment.CurrentManagedThreadId == _mainThreadIdentifier) { Load(); @@ -127,23 +195,26 @@ public static ConsoleContainerSettings Active // Off the main thread, or before the very first load, this is the // last resolved value — never a forbidden Resources call. - return _active; + return _asset; } + set => _override = value; } private static void Load() { - _active = Resources.Load(ResourcesPath); + _asset = Resources.Load(ResourcesPath); _loaded = true; } // Identifying the main thread is what lets Active refuse to touch the // Resources API from anywhere else, so it happens at the earliest - // initialization step available. + // initialization step available. An override left from a previous play + // session (when entering play mode skips the domain reload) is dropped too. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] private static void CaptureMainThread() { _mainThreadIdentifier = Environment.CurrentManagedThreadId; + _override = null; } // Warm the cache on the main thread at startup so console instances that @@ -159,7 +230,7 @@ private static void PreloadOnPlay() [UnityEditor.InitializeOnLoadMethod] private static void PreloadInEditor() { - CaptureMainThread(); + _mainThreadIdentifier = Environment.CurrentManagedThreadId; // The asset database is not guaranteed to answer this early in a // domain reload, so resolve the asset once the editor is idle. Any From ecf4dfb6bad0ac15652d483e55f79cc46741583f Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:23:50 +0300 Subject: [PATCH 13/42] feature: history cursors --- UnityPackage/Runtime/ConsoleInstance.cs | 29 +++++++++++++++++++------ UnityPackage/Runtime/ConsoleMessage.cs | 9 +++++++- UnityPackage/Runtime/ConsoleRegistry.cs | 2 +- UnityPackage/Runtime/MessageBuffer.cs | 1 + 4 files changed, 32 insertions(+), 9 deletions(-) diff --git a/UnityPackage/Runtime/ConsoleInstance.cs b/UnityPackage/Runtime/ConsoleInstance.cs index e7dfdb3..9751504 100644 --- a/UnityPackage/Runtime/ConsoleInstance.cs +++ b/UnityPackage/Runtime/ConsoleInstance.cs @@ -197,11 +197,11 @@ public void Create(ConsoleMessageType type, string source, string content, Excep // the history; threads logging concurrently could otherwise store them out of order. lock (_gate) { - message = new ConsoleMessage(type, source, content, exception, callstack); + message = new ConsoleMessage(this, type, source, content, exception, callstack); _history.Add(message, limit); } - ConsoleRegistry.NotifyMessageAdded(this); + ConsoleRegistry.NotifyMessageAdded(); if (UnityConsoleForwarding.ShouldForward(type)) { @@ -219,7 +219,7 @@ public void Create(ConsoleMessageType type, string source, string content, Excep // allocating when something is actually listening for it. if (HasListener(type)) { - RaiseCreated(type, new ConsoleMessage(type, source, content, exception, null)); + RaiseCreated(type, new ConsoleMessage(this, type, source, content, exception, null)); } #endif } @@ -238,14 +238,14 @@ public void Clear() _history.Clear(); } + // Always reported as a clear, so every viewer drops what it copied even when the + // instance is about to leave the registry. + ConsoleRegistry.NotifyCleared(this); + if (IsDisposed) { ConsoleRegistry.Unregister(this); } - else - { - ConsoleRegistry.NotifyCleared(this); - } #endif } @@ -407,6 +407,21 @@ private static void ForwardToUnityConsole(ConsoleMessageType type, string label, } #if UNITY_EDITOR + /// + /// Copies every message added since into + /// , oldest first, and returns the cursor to resume from. + /// receives the cursor of the oldest message still held, + /// so a reader can tell which of its copies the history has dropped since. + /// + internal long CollectSince(long cursor, List destination, out long startPosition) + { + lock (_gate) + { + startPosition = _history.StartPosition; + return _history.CopySince(cursor, destination); + } + } + /// /// Copies messages created after into /// . Consumed by the viewer for incremental diff --git a/UnityPackage/Runtime/ConsoleMessage.cs b/UnityPackage/Runtime/ConsoleMessage.cs index 097322c..83c7e9d 100644 --- a/UnityPackage/Runtime/ConsoleMessage.cs +++ b/UnityPackage/Runtime/ConsoleMessage.cs @@ -54,8 +54,15 @@ public sealed class ConsoleMessage /// public Exception Exception { get; } - internal ConsoleMessage(ConsoleMessageType type, string source, string content, Exception exception, IReadOnlyList callstack) + /// The instance that created the message. + internal ConsoleInstance Owner { get; } + + /// Cursor of the message within its owner's history; assigned when it is stored. + internal long Position { get; set; } + + internal ConsoleMessage(ConsoleInstance owner, ConsoleMessageType type, string source, string content, Exception exception, IReadOnlyList callstack) { + Owner = owner; Timestamp = DateTime.Now; Sequence = Interlocked.Increment(ref _globalSequence); Type = type; diff --git a/UnityPackage/Runtime/ConsoleRegistry.cs b/UnityPackage/Runtime/ConsoleRegistry.cs index ed94d21..5d6a12e 100644 --- a/UnityPackage/Runtime/ConsoleRegistry.cs +++ b/UnityPackage/Runtime/ConsoleRegistry.cs @@ -80,7 +80,7 @@ internal static void Unregister(ConsoleInstance instance) RaiseChanged(); } - internal static void NotifyMessageAdded(ConsoleInstance instance) + internal static void NotifyMessageAdded() { RaiseChanged(); } diff --git a/UnityPackage/Runtime/MessageBuffer.cs b/UnityPackage/Runtime/MessageBuffer.cs index 174d967..b84ce23 100644 --- a/UnityPackage/Runtime/MessageBuffer.cs +++ b/UnityPackage/Runtime/MessageBuffer.cs @@ -61,6 +61,7 @@ internal void Add(ConsoleMessage message, int limit) Grow(effectiveLimit); } + message.Position = endPosition; items[Wrap(head + count)] = message; count++; endPosition++; From 7e2e73a246fe67c6cda05026443921a1f830ec81 Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:24:30 +0300 Subject: [PATCH 14/42] create: message feed --- UnityPackage/Editor/Window/MessageFeed.cs | 305 ++++++++++++++++++ .../Editor/Window/MessageFeed.cs.meta | 2 + 2 files changed, 307 insertions(+) create mode 100644 UnityPackage/Editor/Window/MessageFeed.cs create mode 100644 UnityPackage/Editor/Window/MessageFeed.cs.meta diff --git a/UnityPackage/Editor/Window/MessageFeed.cs b/UnityPackage/Editor/Window/MessageFeed.cs new file mode 100644 index 0000000..7b64f33 --- /dev/null +++ b/UnityPackage/Editor/Window/MessageFeed.cs @@ -0,0 +1,305 @@ +using System; +using System.Collections.Generic; + +namespace reromanlee.ConsoleContainer.Editor +{ + /// + /// The list of messages one viewer window shows, kept up to date incrementally. + /// + /// Each instance in scope is read from its own cursor, so no message is ever skipped however + /// logging threads interleave. New messages are merged into one chronological stream, filtered + /// by the search text and the enabled types, and counted per type. Messages an instance has + /// since dropped from its history are pruned in batches, so the feed never holds on to them. + /// + /// Main thread only. + /// + internal sealed class MessageFeed + { + private const int TypeCount = 3; + + // Pruning walks the whole feed, so evictions are collected until they are worth it: at + // least this many, and at least a sixteenth of the feed. Bounds how many dropped messages + // can linger, without paying a full pass on every frame of sustained logging. + private const int MinimumPruneBatch = 256; + private const int PruneBatchDivisor = 16; + + private static readonly Comparison BySequence = (left, right) => left.Sequence.CompareTo(right.Sequence); + + // Messages in scope that match the search, of every type, in sequence order. + private readonly List matched = new List(); + + // The subset of matched whose type is enabled; unused while every type is. + private readonly List filtered = new List(); + + private readonly List batch = new List(); + private readonly Dictionary sourceIndices = new Dictionary(); + private readonly int[] counts = new int[TypeCount]; + private readonly bool[] enabledTypes = { true, true, true }; + + private ConsoleInstance[] sources = Array.Empty(); + private long[] cursors = Array.Empty(); + private long[] startPositions = Array.Empty(); + private string search = string.Empty; + private long pendingEvictions; + + /// + /// The messages to show, in chronological order. The list instance changes when the type + /// filter switches between "everything" and a subset, so re-read it after a reload. + /// + internal List Visible => AllTypesEnabled ? matched : filtered; + + /// The current search text; empty when nothing is filtered by text. + internal string Search => search; + + private bool AllTypesEnabled => enabledTypes[0] && enabledTypes[1] && enabledTypes[2]; + + /// How many messages of are in scope and match the search, shown or not. + internal int GetCount(ConsoleMessageType type) => counts[(int)type]; + + internal bool IsTypeEnabled(ConsoleMessageType type) => enabledTypes[(int)type]; + + /// Switches to a new set of instances and reloads everything they hold. + internal void SetSources(ConsoleInstance[] scope) + { + sources = scope ?? Array.Empty(); + cursors = new long[sources.Length]; + startPositions = new long[sources.Length]; + + sourceIndices.Clear(); + for (int i = 0; i < sources.Length; i++) + { + sourceIndices[sources[i]] = i; + } + + Reload(); + } + + /// Applies a case-insensitive search over source and content; returns false when unchanged. + internal bool SetSearch(string text) + { + text ??= string.Empty; + if (string.Equals(text, search, StringComparison.Ordinal)) + { + return false; + } + + search = text; + Reload(); + return true; + } + + /// Shows or hides one message type; returns false when unchanged. + internal bool SetTypeEnabled(ConsoleMessageType type, bool enabled) + { + if (enabledTypes[(int)type] == enabled) + { + return false; + } + + enabledTypes[(int)type] = enabled; + RebuildFiltered(); + return true; + } + + /// Drops everything and reads every source again from its oldest held message. + internal void Reload() + { + matched.Clear(); + filtered.Clear(); + Array.Clear(counts, 0, counts.Length); + Array.Clear(cursors, 0, cursors.Length); + Array.Clear(startPositions, 0, startPositions.Length); + pendingEvictions = 0; + + Update(); + } + + /// Pulls in what was logged since the last call and reports how the visible list changed. + internal FeedChange Update() + { + batch.Clear(); + + for (int i = 0; i < sources.Length; i++) + { + cursors[i] = sources[i].CollectSince(cursors[i], batch, out long startPosition); + + if (startPosition > startPositions[i]) + { + pendingEvictions += startPosition - startPositions[i]; + startPositions[i] = startPosition; + } + } + + FeedChange change = FeedChange.None; + + if (batch.Count > 0) + { + // Each source is already in order; sorting merges them into one stream. + batch.Sort(BySequence); + + foreach (ConsoleMessage message in batch) + { + change |= Add(message); + } + + batch.Clear(); + } + + if (pendingEvictions >= Math.Max(MinimumPruneBatch, matched.Count / PruneBatchDivisor)) + { + change |= Prune(); + } + + return change; + } + + /// Index of in , or -1. + internal int IndexOf(ConsoleMessage message) + { + if (message == null) + { + return -1; + } + + List list = Visible; + int index = LowerBound(list, message.Sequence); + return index < list.Count && ReferenceEquals(list[index], message) ? index : -1; + } + + private FeedChange Add(ConsoleMessage message) + { + if (!Matches(message)) + { + return FeedChange.None; + } + + counts[(int)message.Type]++; + bool appended = Insert(matched, message); + + if (!AllTypesEnabled) + { + if (!enabledTypes[(int)message.Type]) + { + return FeedChange.None; + } + + appended = Insert(filtered, message); + } + + return appended ? FeedChange.Appended : FeedChange.Reordered; + } + + private bool Matches(ConsoleMessage message) + { + return search.Length == 0 + || message.Source.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0 + || message.Content.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0; + } + + private void RebuildFiltered() + { + filtered.Clear(); + if (AllTypesEnabled) + { + return; + } + + foreach (ConsoleMessage message in matched) + { + if (enabledTypes[(int)message.Type]) + { + filtered.Add(message); + } + } + } + + private FeedChange Prune() + { + pendingEvictions = 0; + + int removed = Compact(matched, countRemovals: true); + if (!AllTypesEnabled) + { + removed += Compact(filtered, countRemovals: false); + } + + return removed > 0 ? FeedChange.Reordered : FeedChange.None; + } + + private int Compact(List list, bool countRemovals) + { + int kept = 0; + for (int i = 0; i < list.Count; i++) + { + ConsoleMessage message = list[i]; + if (IsEvicted(message)) + { + if (countRemovals) + { + counts[(int)message.Type]--; + } + + continue; + } + + list[kept++] = message; + } + + int removed = list.Count - kept; + list.RemoveRange(kept, removed); + return removed; + } + + private bool IsEvicted(ConsoleMessage message) + => sourceIndices.TryGetValue(message.Owner, out int index) && message.Position < startPositions[index]; + + // Messages almost always arrive in order and append; one that a concurrent thread logged + // just before the last batch is slotted into place instead. Returns whether it appended. + private static bool Insert(List list, ConsoleMessage message) + { + int count = list.Count; + if (count == 0 || list[count - 1].Sequence < message.Sequence) + { + list.Add(message); + return true; + } + + list.Insert(LowerBound(list, message.Sequence), message); + return false; + } + + // First index whose sequence is not below the given one. + private static int LowerBound(List list, long sequence) + { + int low = 0; + int high = list.Count; + while (low < high) + { + int middle = low + ((high - low) >> 1); + if (list[middle].Sequence < sequence) + { + low = middle + 1; + } + else + { + high = middle; + } + } + + return low; + } + } + + /// How the visible list changed during a . + [Flags] + internal enum FeedChange + { + None = 0, + + /// Messages were added at the end; existing indices are unchanged. + Appended = 1, + + /// Messages were inserted or removed elsewhere; existing indices may have shifted. + Reordered = 2 + } +} diff --git a/UnityPackage/Editor/Window/MessageFeed.cs.meta b/UnityPackage/Editor/Window/MessageFeed.cs.meta new file mode 100644 index 0000000..ed112fa --- /dev/null +++ b/UnityPackage/Editor/Window/MessageFeed.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8a95693ac7b65fdbd24201ca2a50a6ac From 259816e47bef1c2cdee93755a88ce889735f746d Mon Sep 17 00:00:00 2001 From: Roman Likhadievski Date: Thu, 29 Oct 2026 22:30:31 +0300 Subject: [PATCH 15/42] refactor: viewer listview --- UnityPackage/Editor/Window/ConsoleViewer.cs | 769 ++++++++++-------- .../Editor/Window/ConsoleViewer.cs.meta | 3 - UnityPackage/Editor/Window/ConsoleViewer.uss | 239 +++--- UnityPackage/Editor/Window/ConsoleViewer.uxml | 44 +- UnityPackage/Editor/Window/MessageDetails.cs | 144 ++++ .../Editor/Window/MessageDetails.cs.meta | 2 + UnityPackage/Editor/Window/MessageError.uxml | 8 - .../Editor/Window/MessageError.uxml.meta | 10 - UnityPackage/Editor/Window/MessageRow.cs | 66 ++ UnityPackage/Editor/Window/MessageRow.cs.meta | 2 + UnityPackage/Editor/Window/MessageText.uxml | 8 - .../Editor/Window/MessageText.uxml.meta | 10 - .../Editor/Window/MessageWarning.uxml | 8 - .../Editor/Window/MessageWarning.uxml.meta | 10 - UnityPackage/Runtime/ConsoleInstance.cs | 25 - 15 files changed, 768 insertions(+), 580 deletions(-) create mode 100644 UnityPackage/Editor/Window/MessageDetails.cs create mode 100644 UnityPackage/Editor/Window/MessageDetails.cs.meta delete mode 100644 UnityPackage/Editor/Window/MessageError.uxml delete mode 100644 UnityPackage/Editor/Window/MessageError.uxml.meta create mode 100644 UnityPackage/Editor/Window/MessageRow.cs create mode 100644 UnityPackage/Editor/Window/MessageRow.cs.meta delete mode 100644 UnityPackage/Editor/Window/MessageText.uxml delete mode 100644 UnityPackage/Editor/Window/MessageText.uxml.meta delete mode 100644 UnityPackage/Editor/Window/MessageWarning.uxml delete mode 100644 UnityPackage/Editor/Window/MessageWarning.uxml.meta diff --git a/UnityPackage/Editor/Window/ConsoleViewer.cs b/UnityPackage/Editor/Window/ConsoleViewer.cs index de8da4b..cd32fee 100644 --- a/UnityPackage/Editor/Window/ConsoleViewer.cs +++ b/UnityPackage/Editor/Window/ConsoleViewer.cs @@ -1,72 +1,83 @@ using System; using System.Collections.Generic; -using System.Text; using UnityEditor; +using UnityEditor.UIElements; using UnityEditorInternal; using UnityEngine; using UnityEngine.UIElements; namespace reromanlee.ConsoleContainer.Editor { - internal class ConsoleViewer : EditorWindow + /// + /// Editor window listing the messages of one console instance, or of every instance merged in + /// chronological order, with a details pane for the selected message and its clickable call + /// stack. The list is virtualized, so its cost depends on the rows on screen rather than on + /// how many messages exist. + /// + internal sealed class ConsoleViewer : EditorWindow { private const string WindowName = "Console Viewer"; private const string AllInstancesLabel = "All Instances"; - private const string EvenRowClass = "message-container-even"; - private const string SelectedRowClass = "message-container-selected"; + private const string LightThemeClass = "console-viewer--light"; private const string CallstackButtonClass = "callstack-button"; + private const string LoadErrorClass = "console-viewer__load-error"; + private const string CopyCommand = "Copy"; + private const float RowHeight = 18f; - // How close to the bottom (in pixels) the scroll must be to keep following - // new messages. Scrolling up further than this detaches the view; scrolling - // back within it re-attaches. The slack absorbs the per-append layout lag. - private const float StickToBottomSlack = 30f; + // How close to the bottom (in pixels) the list must be to keep following new messages. + // Scrolling up further detaches the view; scrolling back within it re-attaches. + private const float StickToBottomSlack = RowHeight * 2f; + + // Used when the script's default references are missing, so a viewer restored from an old + // layout or a moved package still finds what it is built from. + private const string LayoutGuid = "fbd09c8d7cd32064898d4ed7d266f022"; + private const string DarkIconGuid = "14f03de8a7c5d9543aee0043237d84fa"; + private const string LightIconGuid = "d3ad80c4b750d3748bd70c14e8fddba9"; [SerializeField] private Texture2D windowIconDark; [SerializeField] private Texture2D windowIconLight; - [SerializeField] private VisualTreeAsset consoleViewerAsset; - [SerializeField] private VisualTreeAsset messageTextAsset; - [SerializeField] private VisualTreeAsset messageWarningAsset; - [SerializeField] private VisualTreeAsset messageErrorAsset; - // View state below is serialized per window: EditorWindow fields survive - // domain reloads and are stored in the editor layout, so every window - // instance keeps its own sizes and reopens the way it was left. + // View state below is serialized per window: EditorWindow fields survive domain reloads + // and are stored in the editor layout, so every window reopens the way it was left. [SerializeField] private float detailsPaneSize; [SerializeField] private float callstackPaneSize; [SerializeField] private float scrollOffset; [SerializeField] private string selectedInstanceName = string.Empty; - private DropdownField instanceDropdown; - private VisualElement clearButton; - private VisualElement copyButton; - private VisualElement contentContainer; - private ScrollView contentScrollView; - private Label selectedMessageLabel; - private VisualElement callstackContainer; + private readonly MessageFeed feed = new MessageFeed(); + private readonly HashSet usedInstanceLabels = new HashSet(); + private readonly List instanceLabels = new List(); + private readonly int[] selectionBuffer = new int[1]; + private ToolbarMenu instanceMenu; + private ListView messageList; + private ScrollView messageScrollView; private TwoPaneSplitView mainSplitView; private TwoPaneSplitView detailsSplitView; private VisualElement detailsPane; + private VisualElement callstackPane; + private Label detailsLabel; + private Label detailsInstanceLabel; - private ConsoleMessage selectedMessage; - private VisualElement selectedRow; - - // Dropdown index 0 is always the chronological "All Instances" view; the - // remaining indices map to currentInstances[selectedViewIndex - 1]. + // Index 0 of the instance menu is always the chronological "All Instances" view; the rest + // map to currentInstances[selectedViewIndex - 1]. private ConsoleInstance[] currentInstances = Array.Empty(); + private ConsoleInstance[] feedScope = Array.Empty(); private int selectedViewIndex; - private long lastRenderedSequence; - private int renderedRowCount; + private ConsoleMessage selectedMessage; + private ScrollTarget pendingScroll; + private float pendingScrollOffset; + private Action applyPendingScrollFirst; + private Action applyPendingScrollSecond; private int lastRegistryVersion = -1; private int lastClearGeneration; + private bool isBuilt; + private bool restoreScrollPending; - private readonly List scratch = new List(); - private readonly HashSet usedInstanceLabels = new HashSet(); + // Set from any logging thread; the editor loop does the actual work on the main thread. private volatile bool dirty; - private bool suppressDropdownCallback; - private bool restoreScrollPending; [MenuItem("Tools/Console Viewer")] public static void ShowWindow() @@ -74,74 +85,143 @@ public static void ShowWindow() GetWindow().Show(); } + private ConsoleInstance SelectedInstance => + selectedViewIndex > 0 && selectedViewIndex - 1 < currentInstances.Length + ? currentInstances[selectedViewIndex - 1] + : null; + private void OnEnable() { ApplyWindowChrome(); rootVisualElement.Clear(); - - VisualElement root = consoleViewerAsset.CloneTree(); - root.style.flexGrow = 1; - rootVisualElement.Add(root); - - instanceDropdown = root.Q("instance-dropdown"); - clearButton = root.Q("clear-button"); - copyButton = root.Q("copy-button"); - contentContainer = root.Q("content-container"); - contentScrollView = contentContainer.GetFirstAncestorOfType(); - selectedMessageLabel = root.Q