diff --git a/.github/ConsoleContainerDemo.gif b/.github/ConsoleContainerDemo.gif new file mode 100644 index 0000000..ee06cd2 Binary files /dev/null and b/.github/ConsoleContainerDemo.gif differ diff --git a/.github/readme-console-viewer.gif b/.github/readme-console-viewer.gif deleted file mode 100644 index cff18a9..0000000 Binary files a/.github/readme-console-viewer.gif and /dev/null differ diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..58578a9 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,72 @@ +name: Tests + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +concurrency: + group: tests-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + checks: write + +jobs: + unity: + name: Unity ${{ matrix.unityVersion }} ${{ matrix.testMode }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # Keep in sync with the minimum version in UnityPackage/package.json and the latest supported LTS. + unityVersion: [2022.3.62f3, 6000.0.85f1] + testMode: [EditMode, PlayMode] + env: + UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }} + UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} + UNITY_PASSWORD: ${{ secrets.UNITY_PASSWORD }} + steps: + # Secrets are unavailable to forks and to repositories that have not set them up yet; the job then + # passes with a notice instead of failing, so the workflow stays inert until a license is configured. + - name: Check Unity license + id: license + run: | + if [ -n "$UNITY_LICENSE" ]; then + echo "available=true" >> "$GITHUB_OUTPUT" + else + echo "available=false" >> "$GITHUB_OUTPUT" + echo "::notice::Unity tests skipped. Add the UNITY_LICENSE, UNITY_EMAIL and UNITY_PASSWORD repository secrets to run them." + fi + + # Actions and the game-ci CLI are pinned to exact versions, so the code that receives the Unity secrets + # changes only through a reviewed commit here. + - name: Checkout + if: steps.license.outputs.available == 'true' + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + + - name: Run tests + if: steps.license.outputs.available == 'true' + uses: game-ci/unity-test-runner@32e57712352b500e17974b245a6dce9e11a73213 # v4.4.0 + # A "latest" cliVersion is resolved through the GitHub API, which the action authenticates only via this + # variable, not the githubToken input; unauthenticated calls hit the shared runner IP rate limit (403). + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + cliVersion: v0.1.72 + packageMode: true + projectPath: UnityPackage + unityVersion: ${{ matrix.unityVersion }} + testMode: ${{ matrix.testMode }} + artifactsPath: artifacts + githubToken: ${{ secrets.GITHUB_TOKEN }} + checkName: Unity ${{ matrix.unityVersion }} ${{ matrix.testMode }} results + + - name: Upload results + if: always() && steps.license.outputs.available == 'true' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: test-results-${{ matrix.unityVersion }}-${{ matrix.testMode }} + path: artifacts diff --git a/CHANGELOG.md b/CHANGELOG.md index ecdab83..f6d1392 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,122 +1,28 @@ -# Changelog - -All notable changes to this package are documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -### Changed - -- **The package now lives in the repository's `UnityPackage/` folder.** Git URL - installs must add `?path=/UnityPackage` - (`https://github.com/reromanlee/ConsoleContainer.git?path=/UnityPackage`); an - unpinned URL without it no longer resolves. Installs pinned to `#1.2.0` or - earlier keep working unchanged. - -## [1.2.0] - 2026-08-11 - -### Added - -- **`ConsoleInstance.Created`** — a static event raised right after any instance - finishes constructing, so one subscriber can attach to every instance the - application will ever create, including the ones built later by nested scopes. - Previously a subscriber had to be wired up at each construction site, which - meant a console added later silently went unobserved — the failure mode that - matters most when that subscriber is a crash handler. Handlers see a fully - built instance, run on the constructing thread, and one that throws is reported - through `Debug.LogException` without disturbing the construction that triggered - it. Subscriptions are static and live as long as the domain does. - -## [1.1.0] - 2026-08-11 - -### Added - -- **Message events** — `IConsoleInstance` now raises `MessageCreated` for every - message and `ErrorCreated` for errors, so application code can react to what it - logs (raising a soft crash screen with the error as its reason, for example). - Both fire in player builds as well as the editor, on the thread that logged the - message; a handler that throws is reported through `Debug.LogException` without - disturbing the logging call, and `Dispose` drops every handler. In a build the - `ConsoleMessage` is only allocated when something is subscribed. -- **Parameterless `ConsoleInstance` constructor** — dependency-injection - containers can resolve `IConsoleInstance` by convention instead of failing to - supply the optional name ([#3]). -- **Editor logging settings** — `ConsoleContainerSettings` gained an *Editor - logging* section: a forwarding mode (`Never`, `During Test Runs`, `Always`) and - per-type toggles. Defaulting to *During Test Runs* makes messages show up in the - Test Runner window for the length of a run while leaving the Unity Console clean - the rest of the time, and it works without a settings asset ([#5]). Test-run - detection lives in a separate assembly gated on the Unity Test Framework, so - projects without that package are unaffected. -- **Per-window view state** — each Console Viewer window remembers its splitter - sizes, selected instance and scroll position across domain reloads and editor - restarts, and re-attaches to a recreated instance by name ([#7]). - -### Fixed - -- Instances that share a name no longer collapse into a single dropdown entry - where picking one silently showed another; duplicates are numbered - (`Networking`, `Networking (2)`) ([#4]). -- Disposed instances no longer linger in the dropdown once they have nothing to - show. An instance is dropped when it is disposed while empty, or cleared after - being disposed, so repeated test runs without a domain reload stop stacking - stale entries in front of freshly created ones ([#6]). -- The registry's version counters are now incremented atomically; concurrent - logging could previously lose an update and leave the viewer out of date. -- Loading the settings asset no longer risks touching the main-thread-only - `Resources` API from a background thread, and edits to the asset take effect - without waiting for a domain reload. -- The window title, icon and minimum size are re-applied whenever the window is - enabled, so a viewer restored from a saved layout keeps them. - -## [1.0.0] - 2026-07-09 - -Initial release. - -### Added - -- **Console instances** — `ConsoleInstance` implementing `IConsoleInstance`, - with an optional name passed to the constructor for the viewer dropdown. -- **Three message types** — `CreateText`, `CreateWarning` and `CreateError`, - each with `object` and `string` source overloads plus `params string[]` - content. Source resolves to the string, or the object's type name; content is - the arguments joined by single spaces; the label is `{source}: {content}`. -- **Thread-safe logging** — every `Create*` call is safe from any thread - (jobs, background threads, async), guarded by per-instance locking, an atomic - global sequence number and a thread-safe editor registry. -- **Console Viewer window** (`Tools ▸ Console Viewer`): - - Instance dropdown with an **All Instances** entry that merges every - instance's messages in chronological order. - - `Text` / `Warning` / `Error` rows rendered from visual tree assets, with - per-type icons/colors, `[HH:mm:ss]` timestamps and even-row zebra striping. - - Message selection: the details pane shows the full `{source}: {content}` - text followed by the complete stack trace (like the Unity Console), a - **Copy** button, and the same call stack rendered on the left as buttons - that open the file at its line in the external IDE (top button = the log - call site). - - **Clear** button that clears the selected instance, or all of them when - *All Instances* is selected. - - Incremental rendering (append-only) with auto-scroll when pinned to the - bottom; full rebuilds only on instance-set or clear changes. - - Instances and their messages remain viewable after Play Mode ends (flagged - `(disposed)` in the dropdown) until the next domain reload. -- **Editor vs. player build separation** — in the editor, messages appear only - in the Console Viewer and never reach the Unity Console. -- **Optional build logging** — `ConsoleContainerSettings` ScriptableObject - (Assets ▸ Create ▸ ConsoleContainer ▸ Settings) with an independent toggle per - message type. In player builds, enabled types are forwarded as - `Debug.Log` / `Debug.LogWarning` / `Debug.LogError` of `{source}: {content}`; - with no settings asset in the build, all messages stay hidden. -- **Console Container Demo sample** — an importable MonoBehaviour that logs to - several named instances continuously, including from a background thread. - -[1.0.0]: https://github.com/reromanlee/ConsoleContainer/releases/tag/1.0.0 -[1.1.0]: https://github.com/reromanlee/ConsoleContainer/releases/tag/1.1.0 -[1.2.0]: https://github.com/reromanlee/ConsoleContainer/releases/tag/1.2.0 -[#3]: https://github.com/reromanlee/ConsoleContainer/issues/3 -[#4]: https://github.com/reromanlee/ConsoleContainer/issues/4 -[#5]: https://github.com/reromanlee/ConsoleContainer/issues/5 -[#6]: https://github.com/reromanlee/ConsoleContainer/issues/6 -[#7]: https://github.com/reromanlee/ConsoleContainer/issues/7 +# ConsoleContainer 1.0.0 + +### What's new + +1. Named console instances: `ConsoleInstance` behind a small `IConsoleInstance` interface, logged to through `CreateText`, `CreateWarning` and `CreateError` extension methods with single-message and content overloads, and a string, `Type` or object as the source. +2. Console Viewer window (Window ▸ General ▸ Console Viewer): a virtualized list of one instance or all of them merged chronologically with each message's instance named, type filters with counts, search, a details pane with clickable call stack frames, Copy and Ctrl+C, Clear and Clear on Play, several windows side by side, remembered per-window state, and Dark and Light skin support. +3. `MessageCreated` and `ErrorCreated` events in the editor and player builds, plus the static `ConsoleInstance.Created` to cover every instance at once; throwing handlers are reported without breaking logging, and runaway re-entrant logging is stopped before it can overflow the stack. +4. `CreateException`, which shows where an exception was thrown, hands the original object to handlers through `ConsoleMessage.Exception`, and is forwarded through `Debug.LogException`. +5. Dropped messages in player builds allocate nothing, and a `ConsoleMessage` is only created when a handler is subscribed for its type. +6. Per-type forwarding to the Unity log through an optional settings asset: nothing reaches player logs without one, and in the editor messages are forwarded during test runs only, so they show in the Test Runner window while the Unity Console stays clean. +7. Bounded editor history, 10,000 messages per instance by default, read through per-instance cursors so the viewer never skips a message under concurrent logging. +8. Call stacks that start at the logging call, skip wrappers marked `[HideInCallstack]`, name lambdas and iterators after their method, can be turned off per message type, and are shared between messages logged along the same path. +9. Project Settings ▸ Console Container page that creates the settings asset where the runtime finds it and warns about ignored, editor-only or duplicate assets; `ConsoleContainerSettings.Active` accepts runtime overrides. +10. Thread-safe logging from any thread, culture-independent time text, and cached message text. +11. Console Container Demo sample, Edit Mode and Play Mode test suites, and a GameCI workflow. +12. Unity 2022.3 LTS and Unity 6 support; safe under Mono, IL2CPP, managed code stripping and WebGL. + +### Important + +1. The package lives in the `UnityPackage/` folder of the repository, so git URL installs must end with `?path=/UnityPackage`. + +### Upgrading from internal builds + +1. `MessageType` is now `ConsoleMessageType`, so it no longer clashes with `UnityEditor.MessageType`. +2. Custom `IConsoleInstance` implementations must implement the new core members; calls to `CreateText`, `CreateWarning` and `CreateError` compile unchanged. +3. The Console Viewer moved from Tools ▸ Console Viewer to Window ▸ General ▸ Console Viewer. +4. The `ConsoleMessage` constructor is now internal, and a message without content is labelled with its source alone. +5. Editor history is capped at 10,000 messages per instance, and Clear on Play is on by default. diff --git a/Documentation/FEATURES.md b/Documentation/FEATURES.md new file mode 100644 index 0000000..bc6e755 --- /dev/null +++ b/Documentation/FEATURES.md @@ -0,0 +1,98 @@ +### Features + +A detailed look at what ConsoleContainer does and the guarantees behind it. For setup and code, see [USAGE.md](USAGE.md). + +### Console instances + +A `ConsoleInstance` is a named container of messages, usually one per system: `"Networking"`, `"AI"`, `"Save System"`. Instances are independent, so a system can name its instance after itself without coordinating with anything else; two instances may even share a name, and the viewer numbers them (`Networking`, `Networking (2)`) so each stays selectable. + +1. `new ConsoleInstance("Name")` names the instance; `new ConsoleInstance()` generates a unique `Instance N` name, so dependency-injection containers can construct it by convention. +2. Code depends on `IConsoleInstance`, a deliberately small interface: `Name`, `IsDisposed`, the two message events, `IsEnabled`, `Create`, `Clear` and `Dispose`. The logging shortcuts are extension methods, so they work with any implementation and new ones never break an existing one. +3. `Dispose` stops logging and drops every event handler. A disposed instance that still holds messages stays in the viewer, marked `(disposed)`, until it is cleared; one with nothing to show leaves at once. + +### Message composition + +Every message has a type, a timestamp, a source, content and, in the editor, a call stack. + +| Part | Rule | +| --- | --- | +| **Type** | `Text`, `Warning` or `Error` (`ConsoleMessageType`). | +| **Source** | A `string` as is; a `Type` by its own name, for static classes (`typeof(SaveSystem)`); any other object by its type's name. Generic types read as `List`. Empty or null becomes `null`. | +| **Content** | Content arguments joined with single spaces. | +| **Label** | `{source}: {content}`, or the source alone when there is no content. Shown in the viewer and used for forwarded logs. | +| **TimeText** | `[HH:mm:ss]`, identical on every machine regardless of culture. | +| **Sequence** | A global creation order, so messages from different instances merge chronologically. | + +Source names are cached per type, and `Label` and `TimeText` are built once per message, so repeated reads allocate nothing. + +### Exception logging + +`CreateException(source, exception)` logs an `Error` that reads `{source}: {ExceptionType}: {Message}`. + +1. Its call stack is where the exception was **thrown**, starting at the innermost inner exception, rather than where it was logged. An exception that was never thrown falls back to the logging site. +2. `ConsoleMessage.Exception` hands the original object to handlers, so crash reporters receive a real exception. +3. When forwarded, it goes through `Debug.LogException`, so tools hooked into the Unity log see an exception rather than a string. +4. The viewer lists inner exceptions as `Caused by …` lines. + +### Events + +1. **`MessageCreated`** is raised for every message; **`ErrorCreated`** for errors only, right after it. +2. **`ConsoleInstance.Created`** is static and raised for every instance once it is fully built, so one subscriber covers instances created anywhere, including ones built long afterwards. +3. Events fire **in player builds too**, independent of forwarding: a message that never reaches the Unity log still reaches handlers. +4. Handlers run **on the logging thread**. Marshal to the main thread before touching the Unity API. +5. A **throwing handler** is reported through `Debug.LogException`; the remaining handlers still run and the message is still kept. +6. A handler that **logs from inside a handler** is fine, but nesting is capped at 8 levels per thread. Endless recursion, such as an `ErrorCreated` handler logging an error into the same instance, stops with a single warning instead of a stack overflow that would take the whole process down. + +### The Console Viewer + +Open it from **Window ▸ General ▸ Console Viewer**. + +| Feature | Behaviour | +| --- | --- | +| **Instance menu** | One instance, or **All Instances** merged in chronological order, where each row names its instance on the right, exactly as the menu lists it. Recreated instances are re-attached by name. | +| **Virtualized list** | Only rows on screen exist, so cost depends on the window size, not on how many messages there are. | +| **Type filters** | Toggle Text, Warning and Error, each showing its count (search-aware, capped at `999+`). | +| **Search** | Case-insensitive match over source and content, applied to new messages as they arrive. | +| **Details pane** | Full message, exception causes and a readable stack trace, with selectable text. Very long text is cut for display; Copy keeps all of it. | +| **Call stack buttons** | One per frame, top first; each opens the file at the line in your IDE. Double-click or Enter on a row opens the top frame. | +| **Copy** | The **Copy** button or Ctrl+C in the list copies the message with its full call stack. | +| **Clear / Clear on Play** | Clear the selected instance, or all of them. Clear on Play (on by default, shared by every window) clears everything when play mode starts. | +| **Several windows** | **New Console Viewer** in the tab's menu opens another, so two instances can be watched side by side. | +| **Remembered state** | Each window keeps its instance, filters, search, splitter sizes and scroll position across domain reloads and editor restarts. | +| **Both skins** | Built from Unity's own toolbar and list controls, so it follows the Dark and Light editor themes. | + +### Call stacks + +1. Captured in the editor only, and only when the message type's **Capture call stack** setting is on (it is by default). +2. The top frame is your logging call: the package's own frames are skipped, and so is any method marked with Unity's `[HideInCallstack]`, so a project's own logging wrapper drops out too. +3. Lambdas, iterators and async methods are named after the method they were written in, not the compiler-generated type. +4. Each distinct stack is resolved once and shared by later messages logged along the same path, which keeps repeated logging cheap and retained memory low. + +### Editor history + +1. Each instance keeps up to **10,000** messages by default (`Max Messages Per Instance`; 0 keeps everything), dropping the oldest first. +2. Readers resume from per-instance cursors, so the viewer never skips a message, however logging threads interleave. +3. Player builds keep no history at all. + +### Forwarding to the Unity log + +| Context | Default | Configurable | +| --- | --- | --- | +| **Editor** | Forwarded only **during test runs**, so messages show in the Test Runner window while the Unity Console stays clean the rest of the time. | `Never`, `During Test Runs` or `Always`, plus a toggle per message type. | +| **Player builds** | **Nothing** is forwarded without a settings asset. | A toggle per message type. | + +Forwarded messages use `Debug.Log`, `Debug.LogWarning` and `Debug.LogError` with the message label; exception messages use `Debug.LogException`. The package's frames carry `[HideInCallstack]`, so with **Strip logging callstack** enabled in the Unity Console, double-clicking a forwarded entry opens your call site. + +### Settings + +1. **Project Settings ▸ Console Container** creates the settings asset exactly where the runtime looks for it (`Assets/Resources/ConsoleContainerSettings.asset`) and edits it inline. +2. The page warns about assets the runtime would ignore (wrong name, wrong folder), leave out of builds (a `Resources` folder inside an `Editor` folder), or pick between arbitrarily (more than one). +3. `ConsoleContainerSettings.Active` accepts a settings object created at runtime, overriding the asset without touching it, for QA menus and tests. +4. Settings are safe to read from any thread: the asset is resolved on the main thread and cached at startup. + +### Robustness + +1. Every member of `ConsoleInstance` is safe to call from any thread, including jobs and async code. +2. Logging never throws because of a handler, a destroyed settings override, or a missing settings asset. +3. A viewer whose layout assets are missing shows a readable error instead of a blank, broken window. +4. There is no platform-specific code: the runtime relies only on standard .NET threading primitives and Unity's `Debug` and `Resources` APIs, and was verified in an IL2CPP release player with managed code stripping set to High. diff --git a/Documentation/PERFORMANCE.md b/Documentation/PERFORMANCE.md new file mode 100644 index 0000000..b839ebb --- /dev/null +++ b/Documentation/PERFORMANCE.md @@ -0,0 +1,54 @@ +### Performance + +What ConsoleContainer costs, measured on real Unity runtimes. Numbers are best-of-five averages. + +### Test setup + +1. **IL2CPP:** Unity 6000.0.85f1 Windows x64 release player, managed stripping High, Intel Core i7-12700K. +2. **Mono editor:** Unity 6000.0.85f1 editor with Release code optimization, same machine. +3. **Allocations:** heap growth measured with garbage collection paused, divided by the number of calls. + +Expect several times higher absolute numbers on mobile and WebGL hardware. The relative shape stays the same. + +### Player builds + +Player builds keep no history and capture no call stacks, so a message only costs what it is used for. + +| Message | Time | Allocated | +| --- | --- | --- | +| Dropped (not forwarded, no handler), one message string | 21 ns | 0 B | +| Dropped, three content arguments | 70 ns | 64 B | +| Received by a `MessageCreated` handler | 190 ns | ~98 B | +| Forwarded to `Debug.Log` | ~36 µs | ~6.8 KB | + +1. **Dropped messages allocate nothing.** The logging shortcuts ask the instance whether a message type would have any effect before resolving the source or joining content. +2. **Content arguments cost their array.** `params` arrays are built by the C# compiler at the call site, before the call. Prefer the single-message overload on hot paths, or check `IsEnabled` before building expensive content. +3. **A handler costs one message object.** The `ConsoleMessage` handed to handlers is only created when something is subscribed for that message type. +4. **Forwarding costs what `Debug.Log` costs.** Nearly all of it is Unity's own log call, including its stack trace capture; adjust **Player Settings ▸ Stack Trace** to change that. + +### Editor + +| Message | Time | +| --- | --- | +| With a call stack, logged six calls deep | ~44 µs | +| Without a call stack | 0.2 µs | + +**Call stacks are the cost.** Capturing one is Mono's stack walk, which runs at roughly 3 to 5 µs per managed frame in the editor: about 10 µs with three frames on the stack and 100 µs with twenty-three. Unity's own `StackTraceUtility.ExtractStackTrace` measured 16 to 58 µs on the same stacks. Turn off **Capture call stack** for a message type in the settings when it is logged on a hot path. + +### Editor memory + +| Retained per message | Bytes | +| --- | --- | +| With a call stack | ~125 B plus its text | +| Without a call stack | ~124 B plus its text | + +**Stacks are shared.** Each distinct stack is resolved once and shared by every message logged along the same path, so a call stack adds almost nothing to a message's retained size (382 B per message before sharing). With the default limit of 10,000 messages per instance, a busy instance holds about 1.2 MB plus its messages' text. File paths and method names are stored once for the whole session. + +### Console Viewer + +| Operation | Time | +| --- | --- | +| Take in a burst of 10,000 new messages from three instances | 1.7 ms | +| Apply a search over 30,000 messages | 7.6 ms | + +The list is virtualized: only the rows on screen exist and are re-bound as it scrolls, so drawing cost depends on the window's height, never on the number of messages. New messages are read incrementally, from each instance's own cursor, and merged into the existing list without a rebuild. Logging threads only flip a flag; all work happens on the editor's main loop. diff --git a/Documentation/TESTING.md b/Documentation/TESTING.md new file mode 100644 index 0000000..ecb602a --- /dev/null +++ b/Documentation/TESTING.md @@ -0,0 +1,31 @@ +### Testing + +The package ships its test suite in `UnityPackage/Tests`. It compiles only in projects that opt in, so it costs nothing otherwise. + +### What is covered + +1. **Runtime** (`Tests/Runtime`, Play Mode and players): message composition and source naming, culture-independent time text, sequence ordering, exception logging, `MessageCreated`, `ErrorCreated` and `Created` events, throwing handlers, re-entrant handlers and constructors, disposal, logging from many threads, runtime settings overrides, and zero-allocation paths (dropped messages, cached source names, cached derived text). +2. **Editor** (`Tests/Editor`, Edit Mode): the history ring buffer and its cursors, retention limits, call stack capture (log site, `[HideInCallstack]` wrappers, lambdas, iterators, exceptions and their inner exceptions, per-type toggles, call sites sharing one method), registry lifetime, forwarding modes and per-type toggles, the viewer's message feed (chronological merging, type filters, counts, search, pruning of dropped history, and concurrent logging that never loses a message), details text and truncation, the settings page's asset checks, and the Console Viewer window itself. + +For 1.0.0, both suites passed in the editor on Unity 2022.3.62f3 and Unity 6000.0.85f1. Performance was measured in an IL2CPP Windows release player with managed stripping set to High, see [PERFORMANCE.md](PERFORMANCE.md). + +### Running the tests locally + +Add the package to `testables` in your project's `Packages/manifest.json`, then open **Window ▸ General ▸ Test Runner**: + +```json +{ + "dependencies": { + "com.reromanlee.consolecontainer": "https://github.com/reromanlee/ConsoleContainer.git?path=/UnityPackage" + }, + "testables": [ + "com.reromanlee.consolecontainer" + ] +} +``` + +Run Edit Mode and Play Mode tests in the editor. The tests install a runtime settings override that forwards nothing, so they behave the same whatever settings asset the project has. + +### Continuous integration + +`.github/workflows/tests.yml` runs both suites with [GameCI](https://game.ci) on Unity 2022.3 and Unity 6 for every push to `main` and every pull request. It needs the `UNITY_LICENSE`, `UNITY_EMAIL` and `UNITY_PASSWORD` repository secrets; without them the job passes with a notice instead of failing, so forks stay green. diff --git a/Documentation/USAGE.md b/Documentation/USAGE.md new file mode 100644 index 0000000..f6a6ee0 --- /dev/null +++ b/Documentation/USAGE.md @@ -0,0 +1,156 @@ +### Usage + +Everything beyond the README quick start. The importable **Console Container Demo** sample (Package Manager ▸ ConsoleContainer ▸ Samples) shows these patterns running. + +### Creating instances + +Give each system its own instance and name it after the system, so it shows up under that name in the viewer. Depend on `IConsoleInstance`, and dispose the instance when its owner goes away: + +```csharp +using reromanlee.ConsoleContainer; + +public sealed class NetworkService : IDisposable +{ + private readonly IConsoleInstance console = new ConsoleInstance("Networking"); + + public void Dispose() => console.Dispose(); +} +``` + +`new ConsoleInstance()` generates a unique `Instance N` name, so dependency-injection containers that construct by convention can resolve it. Register a named one through the container's instance API when the name matters: + +```csharp +builder.Register(Lifetime.Singleton); // VContainer, by convention +builder.RegisterInstance(new ConsoleInstance("Networking")); // named +``` + +### Logging + +```csharp +console.CreateText(this, "Connected"); // one message string +console.CreateWarning(this, "Latency high:", latency + "ms"); // content joined with spaces +console.CreateError("Socket", "Connection refused by", host); // a string source +console.CreateText(typeof(SaveSystem), "Loaded"); // a static class +console.CreateException(this, exception); // an exception +``` + +| Source you pass | Shown as | +| --- | --- | +| `"Socket"` | `Socket` | +| `this` in a `NetworkService` | `NetworkService` | +| `typeof(SaveSystem)` | `SaveSystem` | +| a `Dictionary` | `Dictionary` | +| `null` or `""` | `null` | + +Every message is labelled `{source}: {content}`, or just the source when there is no content, so `console.CreateText(this, "Loaded", "42", "assets")` in a `SaveSystem` shows `[14:03:11] SaveSystem: Loaded 42 assets`. + +**On hot paths**, prefer the single-message overload: the `params` overload builds its array at the call site even when the message ends up dropped. For content that is expensive to build, ask first: + +```csharp +if (console.IsEnabled(ConsoleMessageType.Text)) +{ + console.CreateText(this, BuildExpensiveReport()); +} +``` + +`IsEnabled` is always true in the editor, which keeps every message, and in a player build is only true when the type is forwarded or something is subscribed. + +### Logging exceptions + +```csharp +try +{ + socket.Connect(host); +} +catch (SocketException exception) +{ + console.CreateException(this, exception); +} +``` + +The message reads `NetworkService: SocketException: Connection refused`, its call stack is where the exception was thrown, and handlers receive the original object through `message.Exception`. Forwarded, it goes through `Debug.LogException`. + +### Reacting to messages + +```csharp +console.ErrorCreated += message => SoftCrashScreen.Show(message.Label); +console.MessageCreated += message => Telemetry.Record(message.Type, message.Label); +``` + +1. Handlers run in player builds too, even when nothing is forwarded to the Unity log. +2. Handlers run **on the thread that logged**. Marshal to the main thread before touching the Unity API, for example through a `SynchronizationContext` captured on the main thread. +3. A throwing handler is reported through `Debug.LogException` and never breaks the logging call. +4. `Dispose` drops every handler, so a disposed instance cannot keep the objects they captured alive. + +The `ConsoleMessage` a handler receives carries `Type`, `Timestamp`, `Source`, `Content`, `Label`, `TimeText`, `Sequence`, `Exception` and, in the editor, `Callstack`. + +### Covering every instance at once + +Subscribing per instance means remembering to do it wherever one is built. `ConsoleInstance.Created` is static and reaches every instance the application will ever create, including ones built much later: + +```csharp +// Install once, before anything logs. +ConsoleInstance.Created += instance => instance.ErrorCreated += message => CrashReporter.Report(instance.Name, message); +``` + +The instance is fully built when handlers run, on the constructing thread. Subscriptions live as long as the domain does: a static handler needs no unsubscribe, one that is not must detach or it keeps its target alive. When entering play mode skips the domain reload, unsubscribe before subscribing, so a surviving handler is not registered twice. + +### The Console Viewer + +Open **Window ▸ General ▸ Console Viewer**. Pick an instance or **All Instances** from the toolbar menu, filter by type with the count toggles, and type in the search field to match source or content. + +1. Select a row to see the full message and its call stack; each frame button opens the file at its line, and double-click or Enter opens the top one. +2. **Copy**, or Ctrl+C in the list, copies the message with its full call stack. The details text is also selectable. +3. **Clear** clears the selected instance, or all of them under All Instances. **Clear on Play** clears everything when play mode starts; it is shared by every window. +4. **New Console Viewer** in the window tab's menu opens another window with its own view. + +### Writing a logging wrapper + +Mark wrapper methods with Unity's `[HideInCallstack]`, so their frames are skipped and the top frame stays the real call site, in the viewer and, with **Strip logging callstack** enabled, in the Unity Console: + +```csharp +public static class Log +{ + private static readonly IConsoleInstance Gameplay = new ConsoleInstance("Gameplay"); + + [HideInCallstack] + public static void Info(object source, string message) => Gameplay.CreateText(source, message); +} +``` + +### Settings + +Open **Project Settings ▸ Console Container** and choose **Create Settings Asset**, which places it at `Assets/Resources/ConsoleContainerSettings.asset`, where the runtime looks for it. Without an asset, the defaults in the table apply. + +| Setting | Default | Meaning | +| --- | --- | --- | +| **Log Text / Warnings / Errors In Build** | On | Forward each type to `Debug.Log`, `LogWarning`, `LogError` in player builds, once an asset exists. | +| **Editor Forwarding** | During Test Runs | When editor messages are also forwarded: `Never`, `During Test Runs` or `Always`. | +| **Log Text / Warnings / Errors In Editor** | On | Which types are forwarded while editor forwarding is active. | +| **Max Messages Per Instance** | 10,000 | Editor history per instance; the oldest are dropped first. 0 keeps everything. | +| **Capture Text / Warning / Error Callstack** | On | Record a clickable call stack per type in the editor. | + +With no asset at all, nothing reaches the log in player builds. The settings page warns about assets the runtime would ignore or leave out of builds. + +### Test runs + +The Test Runner window only lists entries that pass through Unity's log, so by default messages are forwarded for the length of a test run, and only then. A forwarded error is a `Debug.LogError`, which fails a test unless it is declared with `LogAssert.Expect`, exactly as `Debug`-based code does; turn **Log Errors In Editor** off, or install an override (below), to see errors without failing on them. Test-run detection uses the Unity Test Framework; without it, forwarding during test runs simply never activates. + +### Overriding settings at runtime + +Install a settings object created in code to change behaviour without touching the project asset: a QA menu that turns build logging on, or a test that silences forwarding. Assign `null` to return to the asset. + +```csharp +ConsoleContainerSettings verbose = ScriptableObject.CreateInstance(); +verbose.LogTextInBuild = true; +ConsoleContainerSettings.Active = verbose; + +// Later: +ConsoleContainerSettings.Active = null; +``` + +An override lasts until it is replaced, destroyed, or play mode starts again. Avoid changing the project asset's own properties from code in the editor, since the change persists to disk. + +### Implementing `IConsoleInstance` + +Mocks and adapters implement only the core members: `Name`, `IsDisposed`, `MessageCreated`, `ErrorCreated`, `IsEnabled`, `Create`, `Clear` and `Dispose`. Every shortcut (`CreateText`, `CreateWarning`, `CreateError`, `CreateException`) is an extension method that resolves the source, builds the content and calls `Create`, so it works with any implementation. diff --git a/README.md b/README.md index c6f8f82..9c19486 100644 --- a/README.md +++ b/README.md @@ -1,304 +1,103 @@ -# ConsoleContainer - -A lightweight logging container for Unity that keeps your debug output **out of -the Unity Console** and inside dedicated, per-context windows you control. - -Instead of dumping every message into one shared console, you create named -**console instances** — one per system, feature, or subsystem — and view them in -a purpose-built editor window. Each message keeps its timestamp, source and full -call stack, and every stack frame is clickable straight into your IDE, exactly -like the built-in Unity Console. - -![Console viewer window showcase](.github/readme-console-viewer.gif) - -## Why use it instead of the Unity Console? - -- **No clutter.** Your gameplay/tooling logs live in their own window, so the - Unity Console stays reserved for engine warnings, exceptions and third‑party - noise. -- **Split by context.** Give each system its own instance (`"Networking"`, - `"AI"`, `"Save System"`, …) and debug one context at a time without filtering - through everything else. -- **See everything, in order.** The **All Instances** view merges every - instance's messages into a single chronological stream, so you never lose the - ordering between systems. -- **Jump to code.** Selecting a message lists its call stack as buttons; each - one opens the file at the exact line in your external editor. -- **React to what you log.** Every instance raises `MessageCreated` and - `ErrorCreated`, in the editor *and* in builds, so an error can trigger a soft - crash screen that shows the reason instead of just sitting in a log. A static - `Created` event covers every instance at once, including ones built later. -- **Hide it in builds — or don't.** By default nothing reaches a player build. - An optional settings asset lets you forward messages to `Debug.Log` in builds, - with an independent toggle per message type. -- **Thread-safe.** Log from jobs, background threads or async code without - worrying about where the call comes from. - -## Installation (UPM) - -**Package Manager (git URL)** - -1. `Window ▸ Package Manager` -2. `+` ▸ **Add package from git URL…** -3. Enter: +### About ConsoleContainer - ``` - https://github.com/reromanlee/ConsoleContainer.git?path=/UnityPackage - ``` +Named, per-system log containers for Unity that keep debug output out of the Unity Console and in a searchable viewer with clickable call stacks. -**Or edit `Packages/manifest.json` directly** +Create a `ConsoleInstance` for each system, such as Networking, AI or Save System, and log through it from any thread. The Console Viewer window shows one instance or every instance merged in chronological order, with type filters, search, and stack frames that open in your IDE, while the Unity Console stays reserved for engine and third-party output. -```json -{ - "dependencies": { - "com.reromanlee.consolecontainer": "https://github.com/reromanlee/ConsoleContainer.git?path=/UnityPackage" - } -} -``` +It is built for production: messages raise events in player builds too, so an error can drive a soft-crash screen or a crash reporter. Dropped messages cost nothing in builds, the editor bounds its history, and a throwing or endlessly recursive handler cannot break logging. It has no platform-specific code and runs under Mono and IL2CPP with managed code stripping. -To pin a release, append its tag after the path, e.g. `?path=/UnityPackage#1.3.0`. -Releases up to and including `1.2.0` predate the `UnityPackage` folder and are -installed without `?path`: `https://github.com/reromanlee/ConsoleContainer.git#1.2.0`. +![Console Viewer showcase](.github/ConsoleContainerDemo.gif) -**Or install locally** by cloning the repository anywhere on disk and choosing -`+` ▸ **Add package from disk…** ▸ `UnityPackage/package.json`. +### Features -> Requires **Unity 6000.0 (Unity 6)** or newer. +1. Per-system named console instances +2. Viewer with merged chronological view +3. Clickable call stacks into your IDE +4. Search, type filters and counts +5. Message and error events in builds +6. Exception logging with throw-site stacks +7. Thread-safe logging from any thread +8. Zero-allocation dropped messages +9. Bounded editor history per instance +10. Per-type forwarding to the Unity log +11. Test Runner visibility during test runs +12. Project Settings page, runtime overrides -## Quick start +Detailed about features - see [FEATURES.md](Documentation/FEATURES.md). How the package is tested - see [TESTING.md](Documentation/TESTING.md). -```csharp -using reromanlee.ConsoleContainer; +### Performance -public class NetworkService -{ - // Name the instance so it shows up in the viewer's dropdown. - private readonly IConsoleInstance console = new ConsoleInstance("Networking"); +**Dropped messages cost nothing in builds.** In an IL2CPP release player on an Intel Core i7-12700K, a message that is neither forwarded nor observed costs 21 ns and allocates nothing. A handler receiving it costs about 190 ns and one ~100-byte message object, and forwarding costs what Unity's own `Debug.Log` does. - public void Connect(string host) - { - console.CreateText(this, "Connecting to", host); - console.CreateWarning(this, "Latency high:", "180ms"); - console.CreateError("Socket", "Connection refused by", host); - } -} -``` +**The editor pays for call stacks, not for logging.** Without a call stack a message costs 0.2 µs; capturing one is Mono's stack walk, at roughly 3 to 5 µs per managed frame. Each distinct stack is stored once, so a message retains about 125 bytes plus its text, and the virtualized viewer takes in a burst of 10,000 messages in under 2 ms. -Open the window from **`Tools ▸ Console Viewer`**. +Detailed about performance - see [PERFORMANCE.md](Documentation/PERFORMANCE.md). -### Try the sample +### Requirements -In the Package Manager, select ConsoleContainer and import the **Console -Container Demo** sample. Drop `ConsoleContainerDemo` on a GameObject, press -Play, open the viewer, and switch the dropdown between the running instances -(one of which logs from a background thread). +1. Unity 2022.3 LTS or newer, including Unity 6. +2. Mono or IL2CPP scripting backend. +3. No package dependencies. -## Logging API +### Limitations -`ConsoleInstance` implements `IConsoleInstance`: +1. Call stacks are captured in the editor only. +2. Player builds keep no message history. +3. The viewer is an editor window, not in-game. +4. Handlers run on the logging thread. +5. Messages are text, without structured fields. -```csharp -void CreateText (object source, params string[] messageContent); -void CreateText (string source, params string[] messageContent); -void CreateWarning(object source, params string[] messageContent); -void CreateWarning(string source, params string[] messageContent); -void CreateError (object source, params string[] messageContent); -void CreateError (string source, params string[] messageContent); -``` +### How to install -Every message is composed the same way — think of it like `console.log` in the -browser, where the first argument names the source: +1. **Git URL.** In Unity, open **Window ▸ Package Manager ▸ + ▸ Add package from git URL…** and enter `https://github.com/reromanlee/ConsoleContainer.git?path=/UnityPackage#1.0.0`. Drop `#1.0.0` to track the latest `main` instead of a release. +2. **Manifest.** Add the same URL to `Packages/manifest.json`: -- **Time** — rendered as `[HH:mm:ss]`. -- **Source** — the `string` you pass, or `source.GetType().Name` for the - `object` overload. -- **Content** — every `messageContent` element joined with a single space. -- **Label** — the full line shown in the list and details pane: + ```json + { + "dependencies": { + "com.reromanlee.consolecontainer": "https://github.com/reromanlee/ConsoleContainer.git?path=/UnityPackage#1.0.0" + } + } + ``` - ``` - {source}: {content} - ``` +3. **Tarball.** Download `com.reromanlee.consolecontainer-1.0.0.tgz` from the [latest release](https://github.com/reromanlee/ConsoleContainer/releases/latest), then choose **+ ▸ Add package from tarball…** in the Package Manager. -So `console.CreateText(this, "Loaded", "42", "assets")` from a `SaveSystem` -produces: +The **Console Container Demo** sample can then be imported from the package's **Samples** tab in the Package Manager. -``` -[14:03:11] SaveSystem: Loaded 42 assets -``` +### How to use -### Other members +**Create one instance per system and log through it.** The source is a string, a type, or `this`, which shows as its type name; content arguments are joined with spaces. Dispose the instance when its owner goes away. ```csharp -new ConsoleInstance(); // auto-named "Instance N" -new ConsoleInstance("My Context"); // named for the dropdown - -instance.Name; // the display name -instance.IsDisposed; // true once Dispose has been called -instance.Clear(); // remove this instance's messages -instance.Dispose(); // stop logging and drop event handlers -``` - -Two instances may share a name — the viewer disambiguates them — so a system is -free to name its instance after itself without coordinating with anything else. - -### Dependency injection +using reromanlee.ConsoleContainer; -`ConsoleInstance` has a parameterless constructor next to the named one, so -containers that construct by convention (VContainer, Zenject, Reflex, …) can -resolve `IConsoleInstance` without being taught how to supply a name: +public sealed class NetworkService +{ + private readonly IConsoleInstance console = new ConsoleInstance("Networking"); -```csharp -builder.Register(Lifetime.Singleton); + public void Connect(string host) + { + console.CreateText(this, "Connecting to", host); // NetworkService: Connecting to … + console.CreateWarning("Socket", "Latency high"); // Socket: Latency high + } +} ``` -Register a named instance with the container's own factory/instance API when you -want it to show up under a specific name: +**React to what you log, in the editor and in builds.** `ErrorCreated` and `MessageCreated` fire on the logging thread, and the static `ConsoleInstance.Created` reaches every instance the application will ever create. `CreateException` keeps the exception and the stack where it was thrown. ```csharp -builder.RegisterInstance(new ConsoleInstance("Networking")); -``` - -## Reacting to messages +ConsoleInstance.Created += instance => instance.ErrorCreated += message => SoftCrashScreen.Show(message.Label); -Every instance raises events as messages are created, so application code can act -on what its systems log. The common case is turning an error into a soft crash -that tells the player (or the QA build) what actually went wrong: - -```csharp -IConsoleInstance console = new ConsoleInstance("Networking"); +try { socket.Connect(host); } +catch (SocketException exception) { console.CreateException(this, exception); } +``` -// Errors only. -console.ErrorCreated += message => SoftCrashScreen.Show(message.Label); +**Open Window ▸ General ▸ Console Viewer** to browse messages. In player builds nothing reaches the Unity log until you create a settings asset from **Project Settings ▸ Console Container** and choose, per message type, what is forwarded. -// Everything, when you want to filter or forward it yourself. -console.MessageCreated += message => Telemetry.Record(message.Type, message.Label); -``` +Detailed about usage - see [USAGE.md](Documentation/USAGE.md). -| Event | Raised for | -| --- | --- | -| `MessageCreated` | Every message, of any type. | -| `ErrorCreated` | `Error` messages only, immediately after `MessageCreated`. | - -- **They fire in player builds too**, independent of the settings asset — a - message that never reaches the Unity log still reaches your handlers. -- **They fire on the thread that logged the message.** If you log from a job or - background thread, marshal to the main thread before touching the Unity API. -- **A throwing handler cannot break logging.** The exception is reported through - `Debug.LogException` and the message is stored as usual. -- **`Dispose()` drops every handler**, so a disposed instance can't keep the - objects its handlers captured alive. - -### Covering every instance at once - -Subscribing per instance means remembering to do it at each construction site, -and an app that builds consoles in more than one place — a bootstrap scope and a -view scope, say — will eventually add a third and quietly leave it unobserved. -`ConsoleInstance.Created` closes that gap: it is static, so one subscription -reaches every instance the app will ever create, including ones constructed long -afterwards. +### License -```csharp -// Install once, before anything logs. Every console, present and future, is covered. -ConsoleInstance.Created += instance => instance.ErrorCreated += SoftCrashScreen.Show; -``` +Made by Roman Likhadievski (reromanlee.com). -- **The instance is fully built** by the time handlers run, so subscribing to its - own events from here is safe. -- **It is raised on the constructing thread**, and a handler that throws is - reported through `Debug.LogException` without breaking the construction. -- **Subscriptions are static and live as long as the domain does.** A static - subscriber needs no unsubscribe; one that is not must detach, or it keeps its - target alive. Where the editor is set to enter play mode without a domain - reload, unsubscribe before subscribing so a surviving handler is not left - registered twice. - -The `ConsoleMessage` handed to a handler carries `Type`, `Timestamp`, `Source`, -`Content`, `Label` (`"{source}: {content}"`) and — in the editor — `Callstack`. - -## The Console Viewer window - -| Feature | Behaviour | -| --- | --- | -| **Instance dropdown** | Pick a single instance, or **All Instances** to see every message merged in chronological order. Instances that share a name are numbered (`Networking`, `Networking (2)`) so each stays selectable, and one that ended its life is marked `(disposed)`. | -| **Remembered layout** | Each window keeps its own splitter sizes, selected instance and scroll position across domain reloads and editor restarts. If the instance you were watching is recreated — a new play session, another test run — the view re-attaches to it by name. | -| **Zebra striping** | Alternating rows are subtly highlighted for readability; selection and hover always take priority. | -| **Selection** | Click a message to show its full `{source}: {content}` text in the details pane. | -| **Copy** | Copies the selected message to the system clipboard. | -| **Call stack** | Each frame becomes a button — top button is the log call site, going down the chain — that opens the file at its line in your IDE. | -| **Clear** | Clears the currently selected instance, or **all** of them when *All Instances* is selected. A `(disposed)` instance leaves the dropdown at that point, since it has nothing left to show. | - -## Editor vs. player builds - -**In the Unity Editor**, messages go to the Console Viewer window. They stay out -of the Unity Console — no `Debug.Log`, no doubled-up output — as long as you log -through a `ConsoleInstance` (calling `Debug.Log` or throwing exceptions yourself -still behaves normally). The one exception is test runs, covered -[below](#showing-messages-in-the-test-runner). - -**In a player build**, there is no viewer, so messages are optionally forwarded -to Unity's log based on an optional settings asset: - -1. `Assets ▸ Create ▸ ConsoleContainer ▸ Settings`. -2. Move the created `ConsoleContainerSettings` asset into any **`Resources`** - folder so it ships with the build. -3. Toggle logging **per message type**: - - | Message type | Build output | - | --- | --- | - | Text | `Debug.Log("{source}: {content}")` | - | Warning | `Debug.LogWarning("{source}: {content}")` | - | Error | `Debug.LogError("{source}: {content}")` | - -If **no** settings asset exists in the build, all ConsoleContainer messages stay -hidden. This lets you keep verbose instrumentation in your code and decide, per -project, exactly what (if anything) surfaces in shipped logs. - -### Showing messages in the Test Runner - -The Test Runner window only lists entries that pass through Unity's log handler, -so messages kept inside the Console Viewer would be invisible while tests run. -The same settings asset therefore has an **Editor logging** section: - -| Setting | Meaning | -| --- | --- | -| **Editor forwarding** | `Never`, `During Test Runs` *(default)* or `Always` — when editor messages are mirrored into the Unity console. | -| **Log … in editor** | The same per-type toggles as builds, applied while forwarding is active. | - -With the default, messages appear in the Test Runner for the length of a run — -and, since it is the same log stream, in the Unity Console for that stretch too — -while the console stays clean the rest of the time. No settings asset is needed -for this; the defaults above apply on their own, so create one only to change -them. - -> **Errors fail tests.** A forwarded `CreateError` becomes `Debug.LogError`, and -> Unity fails a test on an unexpected error unless it is declared with -> `LogAssert.Expect`. That mirrors what `Debug`-based code already does; turn -> **Log Errors In Editor** off if you would rather see errors without failing on -> them. - -Test-run detection uses the Unity Test Framework package. Without it installed, -the bridge assembly is skipped and forwarding simply never activates. - -## Performance - -- **Editor-only cost.** Message storage and call-stack capture happen only under - `UNITY_EDITOR`; player builds do nothing beyond the optional `Debug` forward. - A build allocates a `ConsoleMessage` only when something is actually - subscribed to `MessageCreated` or `ErrorCreated`. -- **Incremental rendering.** The viewer appends only *new* rows each editor - frame using a globally monotonic sequence number — it does not rebuild the - whole list on every message. A full rebuild happens only when instances change - or a clear occurs. -- **Off-thread friendly.** Logging never blocks on the UI; the window marshals - all rendering to the editor's main-thread update loop, so background threads - just append under a short lock. -- **Chronological merge is free.** Because sequence numbers are assigned - atomically at creation, the *All Instances* view stays ordered without sorting - the entire history. - -Best suited to typical debugging volumes. For sustained, extremely high-rate -logging, prefer a dedicated instance you can `Clear()` periodically. - -## License - -MIT — see [LICENSE.md](LICENSE.md). \ No newline at end of file +Licensed under MIT - see [LICENSE.md](LICENSE.md). diff --git a/UnityPackage/Editor/AssemblyInfo.cs b/UnityPackage/Editor/AssemblyInfo.cs new file mode 100644 index 0000000..37d4646 --- /dev/null +++ b/UnityPackage/Editor/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +// The package's editor tests exercise the viewer's internal feed and details plumbing. +[assembly: InternalsVisibleTo("reromanlee.ConsoleContainer.Editor.Tests")] diff --git a/UnityPackage/Editor/AssemblyInfo.cs.meta b/UnityPackage/Editor/AssemblyInfo.cs.meta new file mode 100644 index 0000000..cca83ba --- /dev/null +++ b/UnityPackage/Editor/AssemblyInfo.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ce49ef55630ca4734987bab0c7d3ae39 diff --git a/UnityPackage/Editor/Settings.meta b/UnityPackage/Editor/Settings.meta new file mode 100644 index 0000000..0468f60 --- /dev/null +++ b/UnityPackage/Editor/Settings.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 12e31c3def5c0b8bb4ce93f024582bb6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/UnityPackage/Editor/Settings/ConsoleContainerSettingsProvider.cs b/UnityPackage/Editor/Settings/ConsoleContainerSettingsProvider.cs new file mode 100644 index 0000000..7cf4a5f --- /dev/null +++ b/UnityPackage/Editor/Settings/ConsoleContainerSettingsProvider.cs @@ -0,0 +1,223 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEditor.UIElements; +using UnityEngine; +using UnityEngine.UIElements; + +namespace reromanlee.ConsoleContainer.Editor +{ + /// + /// The Project Settings ▸ Console Container page. Shows the settings asset inline, + /// creates it exactly where the runtime looks for it, and warns about copies the runtime would + /// ignore, leave out of builds, or pick between arbitrarily. + /// + internal static class ConsoleContainerSettingsProvider + { + internal const string SettingsPath = "Project/Console Container"; + internal const string DefaultAssetPath = "Assets/Resources/" + ConsoleContainerSettings.ResourcesPath + ".asset"; + + private const string ResourcesFolderName = "Resources"; + private const string EditorFolderSegment = "/Editor/"; + + private static VisualElement _activeRoot; + + [SettingsProvider] + private static SettingsProvider Create() + { + return new SettingsProvider(SettingsPath, SettingsScope.Project) + { + label = "Console Container", + keywords = new HashSet { "Console", "Logging", "Forwarding", "Call stack", "Test Runner", "History" }, + activateHandler = (searchContext, root) => + { + _activeRoot = root; + EditorApplication.projectChanged += Rebuild; + Rebuild(); + }, + deactivateHandler = () => + { + EditorApplication.projectChanged -= Rebuild; + _activeRoot = null; + } + }; + } + + /// Where a settings asset at stands with the runtime lookup. + internal static AssetPlacement Classify(string assetPath) + { + string normalized = assetPath.Replace('\\', '/'); + string fileName = Path.GetFileNameWithoutExtension(normalized); + string folderName = Path.GetFileName(Path.GetDirectoryName(normalized) ?? string.Empty); + + // Resources.Load finds an asset with this name, in any letter case, at the root of a + // Resources folder. + if (!string.Equals(fileName, ConsoleContainerSettings.ResourcesPath, StringComparison.OrdinalIgnoreCase) + || !string.Equals(folderName, ResourcesFolderName, StringComparison.OrdinalIgnoreCase)) + { + return AssetPlacement.Ignored; + } + + // Resources folders inside an Editor folder are left out of player builds. + return normalized.IndexOf(EditorFolderSegment, StringComparison.OrdinalIgnoreCase) >= 0 + ? AssetPlacement.EditorOnly + : AssetPlacement.Loaded; + } + + private static void Rebuild() + { + VisualElement root = _activeRoot; + if (root == null) + { + return; + } + + root.Clear(); + root.style.paddingLeft = 10f; + root.style.paddingRight = 10f; + root.style.paddingTop = 2f; + + Label title = new Label("Console Container"); + title.style.fontSize = 19f; + title.style.unityFontStyleAndWeight = FontStyle.Bold; + title.style.marginBottom = 10f; + root.Add(title); + + List loaded = new List(); + List editorOnly = new List(); + List ignored = new List(); + + foreach (string guid in AssetDatabase.FindAssets("t:" + nameof(ConsoleContainerSettings))) + { + string path = AssetDatabase.GUIDToAssetPath(guid); + switch (Classify(path)) + { + case AssetPlacement.Loaded: + loaded.Add(path); + break; + case AssetPlacement.EditorOnly: + editorOnly.Add(path); + break; + default: + ignored.Add(path); + break; + } + } + + List usable = new List(loaded); + usable.AddRange(editorOnly); + + if (usable.Count == 0) + { + AddNotice(root, HelpBoxMessageType.Info, + "No settings asset exists, so the package defaults apply: nothing is logged in player builds, " + + "and in the editor messages are forwarded to the Unity Console only during test runs."); + + Button create = new Button(() => CreateAsset()) { text = "Create Settings Asset" }; + create.style.alignSelf = Align.FlexStart; + create.style.marginBottom = 8f; + root.Add(create); + } + else + { + if (usable.Count > 1) + { + AddNotice(root, HelpBoxMessageType.Warning, + "Several settings assets can be loaded and Unity picks one of them arbitrarily. Keep only one:\n" + + string.Join("\n", usable)); + } + + AddInspector(root, usable[0]); + } + + if (editorOnly.Count > 0) + { + AddNotice(root, HelpBoxMessageType.Warning, + "These settings assets sit in a Resources folder inside an Editor folder. They apply in the editor " + + $"but are left out of player builds. Move them to {Path.GetDirectoryName(DefaultAssetPath)?.Replace('\\', '/')}:\n" + + string.Join("\n", editorOnly)); + } + + if (ignored.Count > 0) + { + AddNotice(root, HelpBoxMessageType.Warning, + $"These settings assets are ignored. The runtime only loads one named \"{ConsoleContainerSettings.ResourcesPath}\" " + + "placed directly inside a Resources folder:\n" + string.Join("\n", ignored)); + } + } + + private static void AddInspector(VisualElement root, string assetPath) + { + ConsoleContainerSettings asset = AssetDatabase.LoadAssetAtPath(assetPath); + if (asset == null) + { + return; + } + + VisualElement header = new VisualElement(); + header.style.flexDirection = FlexDirection.Row; + header.style.alignItems = Align.Center; + header.style.marginBottom = 6f; + + Label path = new Label(assetPath); + path.style.flexGrow = 1f; + path.style.opacity = 0.75f; + header.Add(path); + + header.Add(new Button(() => + { + Selection.activeObject = asset; + EditorGUIUtility.PingObject(asset); + }) + { + text = "Select" + }); + + root.Add(header); + root.Add(new InspectorElement(asset)); + } + + private static void AddNotice(VisualElement root, HelpBoxMessageType type, string text) + { + HelpBox notice = new HelpBox(text, type); + notice.style.marginBottom = 8f; + root.Add(notice); + } + + private static void CreateAsset() + { + if (AssetDatabase.LoadMainAssetAtPath(DefaultAssetPath) != null) + { + Debug.LogError($"ConsoleContainer: cannot create the settings asset, because {DefaultAssetPath} already exists."); + return; + } + + string folder = Path.GetDirectoryName(DefaultAssetPath)?.Replace('\\', '/'); + if (!string.IsNullOrEmpty(folder) && !AssetDatabase.IsValidFolder(folder)) + { + AssetDatabase.CreateFolder(Path.GetDirectoryName(folder)?.Replace('\\', '/'), Path.GetFileName(folder)); + } + + ConsoleContainerSettings asset = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(asset, DefaultAssetPath); + AssetDatabase.SaveAssets(); + EditorGUIUtility.PingObject(asset); + + Rebuild(); + } + } + + /// Where a settings asset stands with the runtime's Resources lookup. + internal enum AssetPlacement + { + /// Loaded in the editor and in player builds. + Loaded, + + /// Loaded in the editor, but left out of player builds. + EditorOnly, + + /// Never loaded: wrong name, or not directly inside a Resources folder. + Ignored + } +} diff --git a/UnityPackage/Editor/Settings/ConsoleContainerSettingsProvider.cs.meta b/UnityPackage/Editor/Settings/ConsoleContainerSettingsProvider.cs.meta new file mode 100644 index 0000000..19e8a07 --- /dev/null +++ b/UnityPackage/Editor/Settings/ConsoleContainerSettingsProvider.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7c0604e69cfef751dbd518c00d6b36cb diff --git a/UnityPackage/Editor/Window/ClearOnPlay.cs b/UnityPackage/Editor/Window/ClearOnPlay.cs new file mode 100644 index 0000000..39e685f --- /dev/null +++ b/UnityPackage/Editor/Window/ClearOnPlay.cs @@ -0,0 +1,49 @@ +using System; +using UnityEditor; + +namespace reromanlee.ConsoleContainer.Editor +{ + /// + /// The editor-wide "Clear on Play" preference. When on, every instance is cleared as play mode + /// starts, so a project that skips the domain reload on entering play mode behaves like one + /// that doesn't, instead of piling up history across sessions. Stored per user, and shared by + /// every Console Viewer window since it clears data they all show. + /// + [InitializeOnLoad] + internal static class ClearOnPlay + { + private const string PreferenceKey = "reromanlee.ConsoleContainer.ClearOnPlay"; + private const bool DefaultEnabled = true; + + static ClearOnPlay() + { + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + } + + /// Raised after the preference changes, so open windows can update their toggles. + internal static event Action Changed; + + internal static bool Enabled + { + get => EditorPrefs.GetBool(PreferenceKey, DefaultEnabled); + set + { + if (value == Enabled) + { + return; + } + + EditorPrefs.SetBool(PreferenceKey, value); + Changed?.Invoke(); + } + } + + private static void OnPlayModeStateChanged(PlayModeStateChange change) + { + if (change == PlayModeStateChange.ExitingEditMode && Enabled) + { + ConsoleRegistry.ClearAll(); + } + } + } +} diff --git a/UnityPackage/Editor/Window/ClearOnPlay.cs.meta b/UnityPackage/Editor/Window/ClearOnPlay.cs.meta new file mode 100644 index 0000000..06c3dac --- /dev/null +++ b/UnityPackage/Editor/Window/ClearOnPlay.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 69c29afaac0d73d1c94c88f25920b56d diff --git a/UnityPackage/Editor/Window/ConsoleViewer.cs b/UnityPackage/Editor/Window/ConsoleViewer.cs index 0fc868b..0193d24 100644 --- a/UnityPackage/Editor/Window/ConsoleViewer.cs +++ b/UnityPackage/Editor/Window/ConsoleViewer.cs @@ -1,149 +1,278 @@ 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. Several windows can be open at once, each with its own view. + /// + internal sealed class ConsoleViewer : EditorWindow, IHasCustomMenu { 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"; - - // 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; + private const string LoadErrorClass = "console-viewer__load-error"; + private const string TypeIconClass = "console-viewer__type-icon"; + private const string CountOverflowText = "999+"; + private const int MaximumShownCount = 999; + private const string CopyCommand = "Copy"; + private const float RowHeight = 18f; + + // 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; + [SerializeField] private string searchText = string.Empty; + [SerializeField] private bool showText = true; + [SerializeField] private bool showWarnings = true; + [SerializeField] private bool showErrors = true; - 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 Dictionary instanceDisplayNames = new Dictionary(); + private readonly int[] selectionBuffer = new int[1]; + private readonly ToolbarToggle[] typeToggles = new ToolbarToggle[3]; + private readonly int[] shownCounts = { -1, -1, -1 }; + + private ToolbarMenu instanceMenu; + private ToolbarToggle clearOnPlayToggle; + 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")] + [MenuItem("Window/General/Console Viewer")] public static void ShowWindow() { GetWindow().Show(); } - private void OnEnable() + // The tab's context menu opens another viewer, so two instances can be watched side by + // side; each window keeps its own selection, filters and layout. + public void AddItemsToMenu(GenericMenu menu) { - 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