From c27597de5320793cddcdfcba0c6950e68c34f4b6 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Wed, 11 Nov 2026 07:29:33 -0500 Subject: [PATCH 1/6] feat(compono-logging): capture host-wide logs with LogCollector Add an opt-in ILoggerProvider capture path so a Generic Host test can assert across every category the host logs, including categories the test never composes. - Add Category to CapturedLogEntry (intentional behavioral equality change) with MEL-parity naming for composed loggers. - Share one entry-construction path between composed and host capture. - Add LogCollector and AddComponoCapture with per-collector idempotent registration and host-owned disposal. - Add AtLevelOrAbove and InCategory verification filters. - Cover real Generic Host capture, cardinality, disposal, isolation, bounded concurrency, Native AOT, and ApiCompat. - Record ADR-0071 Amendment 1 for ProviderAlias availability on net10.0+ only. - Update package docs, how-to, troubleshooting, API reference, and the compono skill/evals. Implements #164 (B2-B6, PLAN-0072). --- Directory.Packages.props | 21 + ...1-compono-logging-host-wide-log-capture.md | 25 ++ docs/documentation-architecture.md | 9 +- ...t-nothing-logged-at-error-across-a-host.md | 109 +++++ docs/how-to/index.md | 1 + docs/packages/compono-logging.md | 153 ++++++- ...-log-capture-and-dotnet-11-ga-impl-plan.md | 124 ++++-- ...mpono.Logging.CapturedLogEntry.Category.md | 18 + .../Compono.Logging.CapturedLogEntry.md | 1 + ...ngBuilder,Compono.Logging.LogCollector).md | 34 ++ ...Logging.ComponoLoggingBuilderExtensions.md | 19 + ...ing.LogCollector.ClearCapturedEntries().md | 11 + ...gging.LogCollector.GetCapturedEntries().md | 14 + ...ing.LogCollector.GetLastCapturedEntry().md | 14 + ...ono.Logging.LogCollector.LogCollector().md | 10 + .../Compono.Logging.LogCollector.Verify().md | 14 + .../Compono.Logging.LogCollector.md | 30 ++ ...(Microsoft.Extensions.Logging.LogLevel).md | 21 + ...gVerificationBuilder.InCategory(string).md | 25 ++ .../Compono.Logging.LogVerificationBuilder.md | 2 + .../api/Compono.Logging/Compono.Logging.md | 2 + docs/troubleshooting/common-errors.md | 38 ++ docs/troubleshooting/index.md | 3 + mkdocs.yml | 1 + skills/compono/SKILL.md | 4 +- skills/compono/evals/evals.json | 28 ++ skills/compono/references/logging.md | 75 +++- src/Compono.Logging/CapturedLogEntry.cs | 12 + src/Compono.Logging/CapturingLogger.cs | 2 +- src/Compono.Logging/CapturingLogger{T}.cs | 2 +- .../ComponoCaptureRegistration.cs | 18 + .../ComponoLogCollectorLogger.cs | 37 ++ .../ComponoLogCollectorProvider.cs | 68 +++ .../ComponoLoggingBuilderExtensions.cs | 52 +++ src/Compono.Logging/ILogEntrySource.cs | 11 + src/Compono.Logging/LogCollector.cs | 70 +++ src/Compono.Logging/LogEntryCollector.cs | 64 +-- src/Compono.Logging/LogEntryFactory.cs | 69 +++ src/Compono.Logging/LogVerificationBuilder.cs | 30 +- src/Compono.Logging/LoggerCategoryName.cs | 97 ++++ .../LoggerTestingExtensions.cs | 5 +- .../Compono.Logging.AotSmokeTest.csproj | 7 +- test/Compono.Logging.AotSmokeTest/Program.cs | 66 ++- test/Compono.Logging.Tests/CategoryTests.cs | 150 +++++++ .../Compono.Logging.Tests.csproj | 6 +- .../GlobalCategoryType.cs | 3 + .../HostLogCaptureTests.cs | 413 ++++++++++++++++++ .../LogCollectorDisposalAndIsolationTests.cs | 281 ++++++++++++ .../LogCollectorRegistrationTests.cs | 65 +++ ...gVerificationBuilderExtendedFilterTests.cs | 138 ++++++ .../TestCategoryProbe.cs | 35 ++ 51 files changed, 2399 insertions(+), 108 deletions(-) create mode 100644 docs/how-to/assert-nothing-logged-at-error-across-a-host.md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.CapturedLogEntry.Category.md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.ComponoLoggingBuilderExtensions.md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.ClearCapturedEntries().md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.GetCapturedEntries().md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.GetLastCapturedEntry().md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.LogCollector().md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.Verify().md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).md create mode 100644 docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategory(string).md create mode 100644 src/Compono.Logging/ComponoCaptureRegistration.cs create mode 100644 src/Compono.Logging/ComponoLogCollectorLogger.cs create mode 100644 src/Compono.Logging/ComponoLogCollectorProvider.cs create mode 100644 src/Compono.Logging/ComponoLoggingBuilderExtensions.cs create mode 100644 src/Compono.Logging/ILogEntrySource.cs create mode 100644 src/Compono.Logging/LogCollector.cs create mode 100644 src/Compono.Logging/LogEntryFactory.cs create mode 100644 src/Compono.Logging/LoggerCategoryName.cs create mode 100644 test/Compono.Logging.Tests/CategoryTests.cs create mode 100644 test/Compono.Logging.Tests/GlobalCategoryType.cs create mode 100644 test/Compono.Logging.Tests/HostLogCaptureTests.cs create mode 100644 test/Compono.Logging.Tests/LogCollectorDisposalAndIsolationTests.cs create mode 100644 test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs create mode 100644 test/Compono.Logging.Tests/LogVerificationBuilderExtendedFilterTests.cs create mode 100644 test/Compono.Logging.Tests/TestCategoryProbe.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 2c3cff5c..be46b98e 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -185,6 +185,27 @@ + + + + + + + + + + + + + + + + + diff --git a/docs/adr/0071-compono-logging-host-wide-log-capture.md b/docs/adr/0071-compono-logging-host-wide-log-capture.md index 4173f17c..2b99663a 100644 --- a/docs/adr/0071-compono-logging-host-wide-log-capture.md +++ b/docs/adr/0071-compono-logging-host-wide-log-capture.md @@ -510,6 +510,31 @@ the pointer. - **Option 3.** Good: no surface. Bad: the scenario's headline assertion reads as a lambda with an opaque failure message. +### Amendment 1 (2026-11-11) — `[ProviderAlias]` availability is net10.0+ only + +Implementation (PLAN-0072 B2/B3) found that the "Package identity and +dependency graph" fact above — that `ProviderAliasAttribute` is available +from `Microsoft.Extensions.Logging.Abstractions` alone — holds only on +net10.0/net11.0. On net8.0/net9.0 the attribute lives in the concrete +`Microsoft.Extensions.Logging` implementation package, which this package +must not reference (the shipped graph above stays Abstractions-only, and +B7 requires the packed dependency groups to remain byte-for-byte identical +to `main`). Unconditional use failed to compile on net8/net9 with +`CS0246: ProviderAliasAttribute could not be found`. + +Resolution: the `[ProviderAlias("Compono")]` attribute on the internal +provider is compiled only under `NET10_0_OR_GREATER`. Consequences, +unchanged in intent but now explicitly version-scoped: + +- The `Logging:Compono:LogLevel` provider-specific filter rule works on + net10.0/net11.0; tests covering it are `#if NET10_0_OR_GREATER`. +- On net8.0/net9.0, consumers use the global host minimum + (`SetMinimumLevel`) or category `AddFilter` rules instead. +- Host-wide capture, `LogCollector`, filtering, ownership/disposal, and + every other decision in this ADR are unaffected on all four TFMs. + +No public API or dependency changes. + ## Links - Issue [#164](https://github.com/LayeredCraft/compono/issues/164); parent diff --git a/docs/documentation-architecture.md b/docs/documentation-architecture.md index 4f2e2974..8c21867c 100644 --- a/docs/documentation-architecture.md +++ b/docs/documentation-architecture.md @@ -118,7 +118,8 @@ docs/ │ ├── customize-a-member.md │ ├── register-a-type.md │ ├── use-profiles.md -│ └── share-a-value-across-a-test.md +│ ├── share-a-value-across-a-test.md +│ └── assert-nothing-logged-at-error-across-a-host.md ├── cookbook/ │ ├── index.md │ └── `," "why are Debug entries missing + from `LogCollector`"). - `faq.md` — questions that don't map to a single diagnostic but come up repeatedly ("why does Compono fail fast on recursion instead of omitting a value like AutoFixture did" is exactly this shape — a real gap-3 diff --git a/docs/how-to/assert-nothing-logged-at-error-across-a-host.md b/docs/how-to/assert-nothing-logged-at-error-across-a-host.md new file mode 100644 index 00000000..2ffcc8f3 --- /dev/null +++ b/docs/how-to/assert-nothing-logged-at-error-across-a-host.md @@ -0,0 +1,109 @@ +# How Do I Assert Nothing Logged at Error or Above Across a Generic Host? + +Register a `LogCollector` on the host's logging pipeline, run the host, +then verify the collector. The collector is the test-owned capture +destination: it sees every category the host logs to, regardless of which +`ILogger` produced the entry. See +[`Compono.Logging`'s Package Guide](../packages/compono-logging.md#host-wide-capture-logcollector--addcomponocapture) +for the full host-wide semantics. + +## Basic case + +```csharp +using Compono.Logging; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +[Fact] +public async Task Startup_LogsNothingAtErrorOrAbove() +{ + var builder = Host.CreateApplicationBuilder(); + var logs = new LogCollector(); + + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(logs); + + using var app = builder.Build(); + await app.StartAsync(TestContext.Current.CancellationToken); + await app.StopAsync(TestContext.Current.CancellationToken); + + logs.Verify().AtLevelOrAbove(LogLevel.Error).Never(); +} +``` + +`AtLevelOrAbove(LogLevel.Error)` matches `Error`, `Critical`, and anything +else at or above that severity; `LogLevel.None` never matches. `Never()` +fails the test with a message naming the filter and the matching entries, +so a regression reads as: + +```text +Expected exactly 0 call(s) to a log entry matching level Error or above, but received 1. +``` + +## Narrow it to one category + +Add `InCategory` when only one subsystem should be checked. The match is +an exact, ordinal, case-sensitive comparison of the entry's `Category`: + +```csharp +logs.Verify() + .AtLevelOrAbove(LogLevel.Error) + .InCategory("Payments.Gateway") + .Never(); +``` + +For a host entry, `Category` is exactly the string the logging pipeline +passed to `ILoggerProvider.CreateLogger` — normally the full name of the +`ILogger` category type. + +## What the host may not capture + +Compono never changes the host's own filter rules. The default host +minimum level is `Information`, so `Debug` and `Trace` entries never reach +the collector unless the host is configured to allow them: + +```csharp + builder.Logging.SetMinimumLevel(LogLevel.Trace); +``` + +If the host filters a category out with `AddFilter`, that category is +absent from the collector too. This is intentional: the collector reports +what the host actually logged, not what any logger attempted to log. + +## Keep the collector for the whole test + +The test owns the `LogCollector`; the host only writes to it. Disposing the +host stops further capture through that host, but entries already captured +stay readable — so you can assert after `Dispose()`/`await using` without +copying anything out first. A collector can also be shared by more than one +host in the same test; each host keeps appending until it is disposed. + +## Using `WebApplicationFactory` + +The same registration works through `ConfigureLogging`: + +```csharp +public sealed class ApiFactory : WebApplicationFactory +{ + public LogCollector Logs { get; } = new(); + + protected override void ConfigureWebHost(IWebHostBuilder builder) => + builder.ConfigureLogging(logging => + { + logging.ClearProviders(); + logging.AddComponoCapture(Logs); + }); +} +``` + +Then assert `factory.Logs.Verify().AtLevelOrAbove(LogLevel.Error).Never()` +after the request or startup path under test. + +## See also + +- [Host-wide capture](../packages/compono-logging.md#host-wide-capture-logcollector--addcomponocapture) + — Category, filters, ownership, and cardinality rules. +- [Share a Value Across a Test](share-a-value-across-a-test.md) — when a + service under test needs a specific `ILogger` rather than host-wide + capture. diff --git a/docs/how-to/index.md b/docs/how-to/index.md index 4641eb01..640add9a 100644 --- a/docs/how-to/index.md +++ b/docs/how-to/index.md @@ -10,6 +10,7 @@ specific job: - [Register a Type](register-a-type.md) - [Use Profiles](use-profiles.md) - [Share a Value Across a Test](share-a-value-across-a-test.md) +- [Assert Nothing Logged at Error or Above Across a Generic Host](assert-nothing-logged-at-error-across-a-host.md) Looking for something integration-specific — "how do I use NSubstitute" or "how do I use Bogus"? That lives in the relevant diff --git a/docs/packages/compono-logging.md b/docs/packages/compono-logging.md index 5c350730..18a2a862 100644 --- a/docs/packages/compono-logging.md +++ b/docs/packages/compono-logging.md @@ -1,11 +1,15 @@ # Compono.Logging -First-class `Microsoft.Extensions.Logging` testing support — `ILogger`/ +First-class `Microsoft.Extensions.Logging` testing support. `ILogger`/ `ILogger` compose naturally through `UseLogging()`, backed by a hand-written `CapturingLogger`/`CapturingLogger` pair (real scope tracking, thread-safe capture, reflection-free structured-property extraction) and Compono-native `Verify()` verification reusing core -`Compono`'s `CallVerifier` unmodified. See +`Compono`'s `CallVerifier` unmodified. A test-owned `LogCollector` +registered with `AddComponoCapture()` captures a real Generic Host's +*host-wide* output — every category, not just loggers Compono composed — +so a test can assert something like "nothing at `Error` or above was +logged anywhere in the host." See [ADR-0055](../adr/0055-compono-logging-testing-support-package.md) (and its three amendments) for the full decision record and [RESEARCH-0013](../research/0013-compono-logging-testing-design-research.md) @@ -79,7 +83,8 @@ Console.WriteLine(failure.Properties?.First().Key); // "OrderId", e.g. `ClearCapturedEntries()`** — direct inspection, no assertion framework required. - **`logger.Verify()`** — the fluent entry point: - `.AtLevel(level)`, `.WithEventId(id)`, `.WithException()`, + `.AtLevel(level)`, `.AtLevelOrAbove(level)`, `.InCategory(category)`, + `.WithEventId(id)`, `.WithException()`, `.WithMessageContaining(text)`, `.Matching(predicate)`, ending in `.Once()` / `.Never()` / `.Exactly(n)` / `.AtLeast(n)` / `.AtMost(n)` ([ADR-0044 Amendment 22](../adr/0044-compono-testdoubles-v2-overloads-generics-verification.md#amendment-22-2026-09-06-callverifieratleastintatmostint-added-requirement-3s-minimality-preserved-not-reversed)) @@ -99,6 +104,138 @@ Console.WriteLine(failure.Properties?.First().Key); // "OrderId", e.g. A provider-composed logger and a directly-constructed one behave identically — one implementation, not two. +## Host-wide capture: `LogCollector` + `AddComponoCapture` + +Composed loggers only see what Compono composed. A real Generic Host (or +`WebApplicationFactory`, or anything else with an +`Microsoft.Extensions.Logging.ILoggingBuilder`) also logs through +categories your test never composed — framework lifetime messages, +libraries, your own `ILogger` resolved from `host.Services`. Register a +test-owned `LogCollector` to capture all of it: + +```csharp +using Compono.Logging; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +var logs = new LogCollector(); +var builder = Host.CreateApplicationBuilder(); +builder.Logging.ClearProviders(); // optional: drop console/debug noise +builder.Logging.AddComponoCapture(logs); +using var host = builder.Build(); + +// ... start the host, call the code under test ... + +logs.Verify().AtLevelOrAbove(LogLevel.Error).InCategory("Payments").Never(); +``` + +`AddComponoCapture` returns the same builder, so it chains; it also works +from `services.AddLogging(logging => logging.AddComponoCapture(logs))` and +`WebApplicationFactory.ConfigureLogging`. It is additive: it never changes +the host's filter rules. + +```csharp +logs.GetCapturedEntries(); +logs.GetLastCapturedEntry(); +logs.ClearCapturedEntries(); +logs.Verify().AtLevelOrAbove(LogLevel.Warning).AtLeast(1); +``` + +### `Category` + +Every `CapturedLogEntry` carries `Category`: + +- Host-captured entries: the exact string passed to + `ILoggerProvider.CreateLogger(category)`. +- Composed/directly-constructed `CapturingLogger`: the same string + `LoggerFactory.CreateLogger()` produces (full name, `.`-separated + nesting, generic arity and arguments removed, C# keyword names for + built-ins). +- Non-generic `CapturingLogger` and a bare composed `ILogger`: `""`. + +`InCategory` is exact, ordinal, case-sensitive. For prefix/wildcard +matching use `.Matching(entry => ...)`. + +> **Behavioral compatibility note.** `Category` is part of +> `CapturedLogEntry`'s record value equality: two entries identical in +> every other field but produced by different categories are **not** equal +> under `Equals`, `==`, or `!=`. This is an intentional behavioral change +> from earlier previews (not a source or binary breaking change), decided +> in [ADR-0071](../adr/0071-compono-logging-host-wide-log-capture.md). + +### Filters + +Two filters exist for the host-wide scenario and behave identically on a +composed `logger.Verify()` and a `LogCollector.Verify()`: + +- `.AtLevelOrAbove(level)` — `Error` matches `Error` and `Critical`. + `AtLevelOrAbove(LogLevel.None)` matches nothing. +- `.InCategory(category)` — exact ordinal match; `null` throws + `ArgumentNullException`. + +Both produce readable failure text, e.g. `a log entry matching level Error +or above`, `a log entry matching category "Payments"`. + +### Host filtering still applies + +The host's own `LoggerFilterOptions` decides what reaches the collector; +`AddComponoCapture` does not override it. Under a default host (minimum +`Information`), `Debug`/`Trace` are not captured. Lower the host's own +level if you need them: + +```csharp +builder.Logging.SetMinimumLevel(LogLevel.Trace); +// or a category rule: +builder.Logging.AddFilter("Payments", LogLevel.Debug); +``` + +On net10.0/net11.0 the provider carries `[ProviderAlias("Compono")]`, so a +provider-specific rule works too: + +```json +{ "Logging": { "Compono": { "LogLevel": { "Default": "Warning" } } } } +``` + +`LogLevel.None` is never captured on any target framework. On net8.0/net9.0 +the alias attribute is unavailable from `Logging.Abstractions` alone +(documented in ADR-0071 Amendment 1); use `SetMinimumLevel`/`AddFilter` +there. + +### Host vs. composed: separate destinations + +In this release the two capture destinations are deliberately separate: + +- Host loggers (anything created by the host's `ILoggerFactory`, including + a container-resolved `ILogger`) write only to the registered + `LogCollector`. +- Loggers composed by `UseLogging()` keep their own per-logger capture + store, exactly as before. + +`GetCapturedEntries()`/`Verify()` on a host `ILogger` still throw +`InvalidOperationException` (it is not a Compono capturing logger); the +message now points at `LogCollector`/`AddComponoCapture`. Read and verify +through the collector instead. Opt-in forwarding is deferred. + +### Ownership, lifetime, and cardinality + +- The test owns the `LogCollector`. The host owns only its provider. The + collector is never disposed, cleared, or detached by the host and stays + readable after the host is disposed. +- Disposing the host stops new capture through its provider. Held loggers + become disabled (`IsEnabled` is `false`, `Log` is a no-op, `BeginScope` + still returns a usable disposable); entries captured before disposal + remain, and `ClearCapturedEntries()` still works. +- Registering the **same** collector twice on one builder is idempotent: + one provider, one copy of each entry. Different collectors on one builder + each get their own provider and both receive every entry. The same + collector across several hosts receives entries from all of them; + disposing one host stops only that host. +- One private lock per collector guards appends, clears, and reads; reads + return snapshots. There is no static/ambient state, so parallel tests with + their own hosts and collectors do not interfere. +- Activity scopes configured through `LoggerFactoryOptions + .ActivityTrackingOptions` appear in `Scopes` like any other scope. + ## Structured properties and `MessageTemplate` `CapturedLogEntry` carries both the raw `State` (always present, the @@ -107,6 +244,7 @@ escape hatch) and derived, reflection-free structured fields: ```csharp public readonly record struct CapturedLogEntry { + public string Category { get; } // ADR-0071; part of value equality public LogLevel LogLevel { get; } public EventId EventId { get; } public Exception? Exception { get; } @@ -173,7 +311,10 @@ time: latter only possible when `ComponoGeneratedLogging` is explicitly disabled, since it's otherwise excluded from generation, Amendment 4). Most common cause: `UseNSubstitute()` was registered *before* - `UseLogging()` — see "Registration order," below. + `UseLogging()` — see "Registration order," below. A container-resolved + `ILogger` from a real host hits this too: it is the host's logger, + not a Compono one — capture it with `LogCollector`/`AddComponoCapture` + instead. 2. **`LoggingProvider` recognized a closed `ILogger` request but found no generated activation for it** (`InvalidOperationException`, at composition time, at runtime) — the category type isn't reachable from @@ -291,7 +432,9 @@ this section used to describe as unsolved. Deliberately not in this package — see ADR-0055's Decision Outcome for the rationale behind each: -- `ILoggerFactory` composition. +- Composing/replacing a host's `ILoggerFactory`. (A host *provider* that + captures into a test-owned `LogCollector` is supported — see "Host-wide + capture," above.) - Serilog-specific or other logging-provider-specific behavior. - Test-runner output capture/routing (a different problem — `TUnit.Logging.Microsoft`'s concern, not behavior verification). diff --git a/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md b/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md index e631db87..f6b7b41f 100644 --- a/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md +++ b/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md @@ -1,6 +1,6 @@ # [PLAN-0072] `Compono.Logging` Host-Wide Log Capture (Issue #164) + .NET 11 GA Migration -**Status:** In Progress +**Status:** Done **Implements:** [ADR-0071](../adr/0071-compono-logging-host-wide-log-capture.md) (issue [#164](https://github.com/LayeredCraft/compono/issues/164), child of @@ -9,8 +9,9 @@ ADR-0071 is **Accepted** (2026-11-10). The maintainer approved ADR-0071 and this plan, including the review-round-1 clarifications in `768af68`, and B0 is closed. Architectural approval is complete. The accepted planning -artifacts now live on `main` (merged via PR #175). Implementation has -started: B1 (PR 1, .NET 11 GA) is in progress. +artifacts now live on `main` (merged via PR #175). Implementation is +complete: B1 (.NET 11 GA, PR #176) merged, and B2-B7 (host-wide log capture) +are implemented and validated on `feat/164-host-wide-log-capture`. ## Goal @@ -206,7 +207,7 @@ this plan's Notes. Tick B1. - [x] B1.2 net11.0 package ranges (`Directory.Packages.props`) - [x] B1.3 Current-state docs sweep (confirm or fix) - [x] B1.4 Full validation (V1, V3, V6, V7, V8) on 11.0.100, results recorded in Notes -- [ ] B1.5 PR 1 merged +- [x] B1.5 PR 1 merged --- @@ -273,11 +274,11 @@ added to the not-a-capturing-logger message), and `test/Compono.Generators.Tests`' logging tests green (activation unchanged). -- [ ] B2.1 `Category` + shared entry construction refactor -- [ ] B2.2 MEL-parity category naming -- [ ] B2.3 `AtLevelOrAbove` / `InCategory` -- [ ] B2.4 Exception-message sentence -- [ ] B2.5 Tests above, focused suites green +- [x] B2.1 `Category` + shared entry construction refactor +- [x] B2.2 MEL-parity category naming +- [x] B2.3 `AtLevelOrAbove` / `InCategory` +- [x] B2.4 Exception-message sentence +- [x] B2.5 Tests above, focused suites green ### B3: `LogCollector`, internal provider, `AddComponoCapture` @@ -340,11 +341,11 @@ these never reach a `.nuspec`. on all TFMs, and no new `PackageReference` in the shipped project (`git diff src/Compono.Logging/Compono.Logging.csproj` shows none). -- [ ] B3.1 `LogCollector` -- [ ] B3.2 Internal provider/logger (`ISupportExternalScope`, `[ProviderAlias("Compono")]`) -- [ ] B3.3 `AddComponoCapture` with the cardinality rules -- [ ] B3.4 Test-only package wiring -- [ ] B3.5 Core host tests green +- [x] B3.1 `LogCollector` +- [x] B3.2 Internal provider/logger (`ISupportExternalScope`, `[ProviderAlias("Compono")]`) +- [x] B3.3 `AddComponoCapture` with the cardinality rules +- [x] B3.4 Test-only package wiring +- [x] B3.5 Core host tests green ### B4: edge cases, concurrency, isolation, negative tests @@ -394,10 +395,10 @@ only to fix defects these tests reveal (note any in Notes). **Acceptance:** `dotnet test test/Compono.Logging.Tests` green; then **full** `dotnet build && dotnet test` green (the first full run on PR 2). -- [ ] B4.1 Cardinality + disposal -- [ ] B4.2 Isolation + bounded concurrency -- [ ] B4.3 Separation, host-logger misuse, activity scopes, exceptions -- [ ] B4.4 Full suite green +- [x] B4.1 Cardinality + disposal +- [x] B4.2 Isolation + bounded concurrency +- [x] B4.3 Separation, host-logger misuse, activity scopes, exceptions +- [x] B4.4 Full suite green ### B5: Native AOT + package compatibility @@ -429,9 +430,9 @@ assertion is missing for `Compono.Logging`). **Acceptance:** V3 (Logging leg), V5, V6, V7 pass, with results recorded in Notes. -- [ ] B5.1 AOT smoke test extended, publish clean, binary passes -- [ ] B5.2 Pack-and-consume -- [ ] B5.3 ApiCompat + nuspec dependency check +- [x] B5.1 AOT smoke test extended, publish clean, binary passes +- [x] B5.2 Pack-and-consume +- [x] B5.3 ApiCompat + nuspec dependency check ### B6: docs, examples, API reference, `compono` skill @@ -478,10 +479,10 @@ Notes. regeneration, V8 passes, every relative link resolves, and the docs describe only shipped behavior. -- [ ] B6.1 Package doc + recipe + troubleshooting -- [ ] B6.2 API reference regenerated -- [ ] B6.3 Skill reference + evals -- [ ] B6.4 Link and validation checks +- [x] B6.1 Package doc + recipe + troubleshooting +- [x] B6.2 API reference regenerated +- [x] B6.3 Skill reference + evals +- [x] B6.4 Link and validation checks ### B7: final integration and release-readiness gate @@ -514,8 +515,8 @@ and B4, B5, and B6 done. - Set PLAN-0072 to `Done`, tick all tasks, and close the beads. The PR references #164 (it closes #164, not #161). -- [ ] B7.1 Full validation green -- [ ] B7.2 Acceptance-criteria cross-check table in Notes +- [x] B7.1 Full validation green +- [x] B7.2 Acceptance-criteria cross-check table in Notes - [ ] B7.3 Plan closeout, PR 2 opened with product-owner approval ### B0: product-owner acceptance (precedes everything) @@ -655,3 +656,72 @@ python3 -c "import json;json.load(open('skills/compono/evals/evals.json'))" - Preview/RC grep: the only tracked match outside `docs/adr`, `docs/research`, `docs/plans`, `docs/reference/api` is the intentional RC.1 history line in `package-validation.yaml`. + +- 2026-11-11 (B2-B6 implementation, branch `feat/164-host-wide-log-capture`): + - Source: `CapturedLogEntry.Category`; one shared entry-construction path + (`LogEntryFactory`) used by both `LogEntryCollector` and the host + provider; `LoggerCategoryName` reproduces MEL's + `TypeNameHelper.GetTypeDisplayName` result without reflection beyond + trim-safe `Type` name properties; `LogCollector` + + `ComponoLoggingBuilderExtensions.AddComponoCapture`; internal + `ComponoLogCollectorProvider`/`ComponoLogCollectorLogger` with + `ISupportExternalScope`; `AtLevelOrAbove` + `InCategory` on + `LogVerificationBuilder` via the internal `ILogEntrySource` seam. + Registration is idempotent per collector instance without + `TryAddEnumerable`, so two distinct collectors on one builder each get + a provider. + - `ProviderAliasAttribute` availability correction: it is in + `Logging.Abstractions` only for net10.0/net11.0, not net8.0/net9.0. + The attribute is compiled under `#if NET10_0_OR_GREATER`, the shipped + dependency graph is unchanged, and the alias config rule is tested + only on net10/net11. Recorded as ADR-0071 Amendment 1 (2026-11-11). + - Tests: `test/Compono.Logging.Tests` 490 passed / 0 failed across + net8.0/net9.0/net10.0/net11.0. New coverage: MEL category parity + against a real `LoggerFactory` probe (including nested, generic, + global-namespace, built-in and array categories), equality regression + for `Category`, both new filters and their failure text, real Generic + Host capture (arbitrary/container categories, host lifetime, every + entry field, `[LoggerMessage]`, scopes across `await`, sibling-task + isolation, activity scopes), host filtering (default + Information minimum, `SetMinimumLevel`, `AddFilter`, net10+ alias), + cardinality, disposal (post-dispose loggers disabled, entries remain + readable, `Clear` still works, double dispose safe, two-host + independence), isolation, and bounded concurrency. + - Validation (B7): `dotnet build Compono.slnx -c Release` 0 warnings / + 0 errors; `dotnet test Compono.slnx -c Release --no-build` 7033 + total, 0 failed, 6532 succeeded, 501 skipped. + - AOT (V3 logging leg): pack-and-publish `net10.0`/`osx-arm64` + `PublishAot=true` binary passed, host-wide capture and category + parity assertions included, and the publish emitted zero IL2xxx/ + IL3xxx warnings. `verify-packaging.sh` passed. + - ApiCompat (V6): packed `Compono.Logging` against + `1.4.0-preview.125` (current nuget.org latest) with no `CP` errors; + only additions. Packed nuspec dependency groups are identical to that + baseline package's groups (V7), and + `inspect-packed-nupkgs.tests.sh` passed. + - API reference regenerated with `.github/scripts/generate-api-reference.sh`; + post-generation status contains only the intended new/changed + `Compono.Logging` pages. Skill validation: `evals.json` parses (62 + evals) and skill-creator `quick_validate.py` reports "Skill is valid!". + - Docs: `docs/packages/compono-logging.md` host-wide section (Category, + filters, host filtering, separate destinations, ownership/cardinality, + activity scopes, intentional equality change); + `docs/how-to/assert-nothing-logged-at-error-across-a-host.md` (nav + + index + documentation architecture); troubleshooting entries for + host `ILogger` `Verify()` and missing Debug entries; + `skills/compono/references/logging.md` + `SKILL.md`; two new evals. + - Release-note line for the v1.4.0 draft author (not edited here): + "`Compono.Logging`: `CapturedLogEntry` equality now includes the new + `Category` property. This is a behavioral change to value equality, + not a source or binary breaking change." + - Acceptance criteria cross-check for #164: + + | # | Criterion | Evidence | + |---|---|---| + | 1 | Host-created loggers of any category captured | `HostLogCaptureTests` arbitrary/container/lifetime categories; AOT host smoke | + | 2 | Category + existing fields exposed | `CapturedLogEntry.Category`; `HostLogCaptureTests` field assertions | + | 3 | Existing `Verify()` vocabulary + level threshold | `AtLevelOrAbove`/`InCategory` tests; headline Generic Host test | + | 4 | Composed capture unchanged | Existing suite unchanged; category parity and separation tests | + | 5 | Host/composed relationship documented | ADR-0071; package doc "Host vs. composed"; logging skill | + | 6 | No new package dependency | `Compono.Logging.csproj` unchanged; packed dependency groups identical | + | 7 | Native AOT/trimming retained | `IsAotCompatible` unchanged; AOT smoke publish zero IL warnings | diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.CapturedLogEntry.Category.md b/docs/reference/api/Compono.Logging/Compono.Logging.CapturedLogEntry.Category.md new file mode 100644 index 00000000..1e7bfdfc --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.CapturedLogEntry.Category.md @@ -0,0 +1,18 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[CapturedLogEntry](Compono.Logging.CapturedLogEntry.md 'Compono\.Logging\.CapturedLogEntry') + +## CapturedLogEntry\.Category Property + +The logger's category \- the exact string passed to +[Microsoft\.Extensions\.Logging\.ILoggerProvider\.CreateLogger\(System\.String\)](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.iloggerprovider.createlogger#microsoft-extensions-logging-iloggerprovider-createlogger(system-string) 'Microsoft\.Extensions\.Logging\.ILoggerProvider\.CreateLogger\(System\.String\)') for a host\-captured entry, or the +`LoggerFactory.CreateLogger()`\-equivalent name for a composed/directly +constructed [CapturingLogger<T>](Compono.Logging.CapturingLogger_T_.md 'Compono\.Logging\.CapturingLogger\')\. The non\-generic [CapturingLogger](Compono.Logging.CapturingLogger.md 'Compono\.Logging\.CapturingLogger') +\(and a bare [Microsoft\.Extensions\.Logging\.ILogger](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger 'Microsoft\.Extensions\.Logging\.ILogger')\) uses the empty string\. This is part of the record's +value equality \(ADR\-0071's one intentional behavioral compatibility change\)\. + +```csharp +public string Category { get; } +``` + +#### Property Value +[System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.CapturedLogEntry.md b/docs/reference/api/Compono.Logging/Compono.Logging.CapturedLogEntry.md index 4469d4e7..bce7b3df 100644 --- a/docs/reference/api/Compono.Logging/Compono.Logging.CapturedLogEntry.md +++ b/docs/reference/api/Compono.Logging/Compono.Logging.CapturedLogEntry.md @@ -17,6 +17,7 @@ Implements [System\.IEquatable<](https://learn.microsoft.com/en-us/dotnet/api | Properties | | | :--- | :--- | +| [Category](Compono.Logging.CapturedLogEntry.Category.md 'Compono\.Logging\.CapturedLogEntry\.Category') | The logger's category \- the exact string passed to [Microsoft\.Extensions\.Logging\.ILoggerProvider\.CreateLogger\(System\.String\)](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.iloggerprovider.createlogger#microsoft-extensions-logging-iloggerprovider-createlogger(system-string) 'Microsoft\.Extensions\.Logging\.ILoggerProvider\.CreateLogger\(System\.String\)') for a host\-captured entry, or the `LoggerFactory.CreateLogger()`\-equivalent name for a composed/directly constructed [CapturingLogger<T>](Compono.Logging.CapturingLogger_T_.md 'Compono\.Logging\.CapturingLogger\')\. The non\-generic [CapturingLogger](Compono.Logging.CapturingLogger.md 'Compono\.Logging\.CapturingLogger') \(and a bare [Microsoft\.Extensions\.Logging\.ILogger](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger 'Microsoft\.Extensions\.Logging\.ILogger')\) uses the empty string\. This is part of the record's value equality \(ADR\-0071's one intentional behavioral compatibility change\)\. | | [EventId](Compono.Logging.CapturedLogEntry.EventId.md 'Compono\.Logging\.CapturedLogEntry\.EventId') | The [EventId](Compono.Logging.CapturedLogEntry.EventId.md 'Compono\.Logging\.CapturedLogEntry\.EventId') passed to the logging call\. | | [Exception](Compono.Logging.CapturedLogEntry.Exception.md 'Compono\.Logging\.CapturedLogEntry\.Exception') | The exception passed to the logging call, if any\. | | [LogLevel](Compono.Logging.CapturedLogEntry.LogLevel.md 'Compono\.Logging\.CapturedLogEntry\.LogLevel') | The level this entry was logged at\. Never [Microsoft\.Extensions\.Logging\.LogLevel\.None](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel.none 'Microsoft\.Extensions\.Logging\.LogLevel\.None') \- a [Microsoft\.Extensions\.Logging\.LogLevel\.None](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel.none 'Microsoft\.Extensions\.Logging\.LogLevel\.None') call is never captured in the first place\. | diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md b/docs/reference/api/Compono.Logging/Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md new file mode 100644 index 00000000..daad7dd0 --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md @@ -0,0 +1,34 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[ComponoLoggingBuilderExtensions](Compono.Logging.ComponoLoggingBuilderExtensions.md 'Compono\.Logging\.ComponoLoggingBuilderExtensions') + +## ComponoLoggingBuilderExtensions\.AddComponoCapture\(this ILoggingBuilder, LogCollector\) Method + +Registers [collector](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md#Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).collector 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)\.collector') as a Compono logging provider on +[builder](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md#Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).builder 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)\.builder')\. Every host logger's entries are then appended to the collector +\(subject to the host's own filter rules\) and inspectable via +[GetCapturedEntries\(\)](Compono.Logging.LogCollector.GetCapturedEntries().md 'Compono\.Logging\.LogCollector\.GetCapturedEntries\(\)')/[Verify\(\)](Compono.Logging.LogCollector.Verify().md 'Compono\.Logging\.LogCollector\.Verify\(\)')\. This never +changes filter rules\. Registering the same collector twice is idempotent \(one provider, no +duplicate entries\); registering distinct collectors adds one provider per collector, and each +receives every entry\. Returns [builder](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md#Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).builder 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)\.builder') for chaining\. + +```csharp +public static Microsoft.Extensions.Logging.ILoggingBuilder AddComponoCapture(this Microsoft.Extensions.Logging.ILoggingBuilder builder, Compono.Logging.LogCollector collector); +``` +#### Parameters + + + +`builder` [Microsoft\.Extensions\.Logging\.ILoggingBuilder](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.iloggingbuilder 'Microsoft\.Extensions\.Logging\.ILoggingBuilder') + + + +`collector` [LogCollector](Compono.Logging.LogCollector.md 'Compono\.Logging\.LogCollector') + +#### Returns +[Microsoft\.Extensions\.Logging\.ILoggingBuilder](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.iloggingbuilder 'Microsoft\.Extensions\.Logging\.ILoggingBuilder') + +#### Exceptions + +[System\.ArgumentNullException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception 'System\.ArgumentNullException') +[builder](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md#Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).builder 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)\.builder') or + [collector](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md#Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).collector 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)\.collector') is [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.ComponoLoggingBuilderExtensions.md b/docs/reference/api/Compono.Logging/Compono.Logging.ComponoLoggingBuilderExtensions.md new file mode 100644 index 00000000..5e28653f --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.ComponoLoggingBuilderExtensions.md @@ -0,0 +1,19 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging') + +## ComponoLoggingBuilderExtensions Class + +Host integration entry point \- registers a test\-owned [LogCollector](Compono.Logging.LogCollector.md 'Compono\.Logging\.LogCollector') as a logging +provider so every host logger's output lands in it\. Named to avoid any ambiguity with +`Microsoft.Extensions.Logging.LoggingBuilderExtensions`\. See +docs/adr/0071\-compono\-logging\-host\-wide\-log\-capture\.md\. + +```csharp +public static class ComponoLoggingBuilderExtensions +``` + +Inheritance [System\.Object](https://learn.microsoft.com/en-us/dotnet/api/system.object 'System\.Object') → ComponoLoggingBuilderExtensions + +| Methods | | +| :--- | :--- | +| [AddComponoCapture\(this ILoggingBuilder, LogCollector\)](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)') | Registers [collector](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md#Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).collector 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)\.collector') as a Compono logging provider on [builder](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md#Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).builder 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)\.builder')\. Every host logger's entries are then appended to the collector \(subject to the host's own filter rules\) and inspectable via [GetCapturedEntries\(\)](Compono.Logging.LogCollector.GetCapturedEntries().md 'Compono\.Logging\.LogCollector\.GetCapturedEntries\(\)')/[Verify\(\)](Compono.Logging.LogCollector.Verify().md 'Compono\.Logging\.LogCollector\.Verify\(\)')\. This never changes filter rules\. Registering the same collector twice is idempotent \(one provider, no duplicate entries\); registering distinct collectors adds one provider per collector, and each receives every entry\. Returns [builder](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md#Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).builder 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)\.builder') for chaining\. | diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.ClearCapturedEntries().md b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.ClearCapturedEntries().md new file mode 100644 index 00000000..995969be --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.ClearCapturedEntries().md @@ -0,0 +1,11 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[LogCollector](Compono.Logging.LogCollector.md 'Compono\.Logging\.LogCollector') + +## LogCollector\.ClearCapturedEntries\(\) Method + +Discards every entry captured so far\. The collector stays fully usable afterward \- + clearing never detaches it from a host that is still capturing into it\. + +```csharp +public void ClearCapturedEntries(); +``` \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.GetCapturedEntries().md b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.GetCapturedEntries().md new file mode 100644 index 00000000..1e65f98e --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.GetCapturedEntries().md @@ -0,0 +1,14 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[LogCollector](Compono.Logging.LogCollector.md 'Compono\.Logging\.LogCollector') + +## LogCollector\.GetCapturedEntries\(\) Method + +Every entry captured so far, oldest first \- a snapshot, safe to read while logging + continues on other threads\. + +```csharp +public System.Collections.Generic.IReadOnlyList GetCapturedEntries(); +``` + +#### Returns +[System\.Collections\.Generic\.IReadOnlyList<](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1 'System\.Collections\.Generic\.IReadOnlyList\`1')[CapturedLogEntry](Compono.Logging.CapturedLogEntry.md 'Compono\.Logging\.CapturedLogEntry')[>](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1 'System\.Collections\.Generic\.IReadOnlyList\`1') \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.GetLastCapturedEntry().md b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.GetLastCapturedEntry().md new file mode 100644 index 00000000..e23e8b2a --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.GetLastCapturedEntry().md @@ -0,0 +1,14 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[LogCollector](Compono.Logging.LogCollector.md 'Compono\.Logging\.LogCollector') + +## LogCollector\.GetLastCapturedEntry\(\) Method + +The most recently captured entry, or [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null') if nothing has been + captured yet\. + +```csharp +public System.Nullable GetLastCapturedEntry(); +``` + +#### Returns +[System\.Nullable<](https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1 'System\.Nullable\`1')[CapturedLogEntry](Compono.Logging.CapturedLogEntry.md 'Compono\.Logging\.CapturedLogEntry')[>](https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1 'System\.Nullable\`1') \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.LogCollector().md b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.LogCollector().md new file mode 100644 index 00000000..8fe27200 --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.LogCollector().md @@ -0,0 +1,10 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[LogCollector](Compono.Logging.LogCollector.md 'Compono\.Logging\.LogCollector') + +## LogCollector\(\) Constructor + +Creates an empty, test\-owned collector\. + +```csharp +public LogCollector(); +``` \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.Verify().md b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.Verify().md new file mode 100644 index 00000000..1eef07d2 --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.Verify().md @@ -0,0 +1,14 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[LogCollector](Compono.Logging.LogCollector.md 'Compono\.Logging\.LogCollector') + +## LogCollector\.Verify\(\) Method + +The entry point for fluent verification over this collector's entries, e\.g\. +`logs.Verify().AtLevelOrAbove(LogLevel.Error).Never()`\. + +```csharp +public Compono.Logging.LogVerificationBuilder Verify(); +``` + +#### Returns +[LogVerificationBuilder](Compono.Logging.LogVerificationBuilder.md 'Compono\.Logging\.LogVerificationBuilder') \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.md b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.md new file mode 100644 index 00000000..51b67df3 --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogCollector.md @@ -0,0 +1,30 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging') + +## LogCollector Class + +A test\-owned sink for host\-wide logging output\. Register one with +[AddComponoCapture\(this ILoggingBuilder, LogCollector\)](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)') on a host's +[Microsoft\.Extensions\.Logging\.ILoggingBuilder](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.iloggingbuilder 'Microsoft\.Extensions\.Logging\.ILoggingBuilder'), then inspect it with +[GetCapturedEntries\(\)](Compono.Logging.LogCollector.GetCapturedEntries().md 'Compono\.Logging\.LogCollector\.GetCapturedEntries\(\)')/[GetLastCapturedEntry\(\)](Compono.Logging.LogCollector.GetLastCapturedEntry().md 'Compono\.Logging\.LogCollector\.GetLastCapturedEntry\(\)') or verify it with +[Verify\(\)](Compono.Logging.LogCollector.Verify().md 'Compono\.Logging\.LogCollector\.Verify\(\)') \- the same verification surface [LoggerTestingExtensions](Compono.Logging.LoggerTestingExtensions.md 'Compono\.Logging\.LoggerTestingExtensions') offers +for a composed logger\. The collector is thread\-safe, is never disposed or reset by the host, and +stays readable after the host is disposed\. See +docs/adr/0071\-compono\-logging\-host\-wide\-log\-capture\.md\. + +```csharp +public sealed class LogCollector +``` + +Inheritance [System\.Object](https://learn.microsoft.com/en-us/dotnet/api/system.object 'System\.Object') → LogCollector + +| Constructors | | +| :--- | :--- | +| [LogCollector\(\)](Compono.Logging.LogCollector.LogCollector().md 'Compono\.Logging\.LogCollector\.LogCollector\(\)') | Creates an empty, test\-owned collector\. | + +| Methods | | +| :--- | :--- | +| [ClearCapturedEntries\(\)](Compono.Logging.LogCollector.ClearCapturedEntries().md 'Compono\.Logging\.LogCollector\.ClearCapturedEntries\(\)') | Discards every entry captured so far\. The collector stays fully usable afterward \- clearing never detaches it from a host that is still capturing into it\. | +| [GetCapturedEntries\(\)](Compono.Logging.LogCollector.GetCapturedEntries().md 'Compono\.Logging\.LogCollector\.GetCapturedEntries\(\)') | Every entry captured so far, oldest first \- a snapshot, safe to read while logging continues on other threads\. | +| [GetLastCapturedEntry\(\)](Compono.Logging.LogCollector.GetLastCapturedEntry().md 'Compono\.Logging\.LogCollector\.GetLastCapturedEntry\(\)') | The most recently captured entry, or [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null') if nothing has been captured yet\. | +| [Verify\(\)](Compono.Logging.LogCollector.Verify().md 'Compono\.Logging\.LogCollector\.Verify\(\)') | The entry point for fluent verification over this collector's entries, e\.g\. `logs.Verify().AtLevelOrAbove(LogLevel.Error).Never()`\. | diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).md b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).md new file mode 100644 index 00000000..dcf865bf --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).md @@ -0,0 +1,21 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[LogVerificationBuilder](Compono.Logging.LogVerificationBuilder.md 'Compono\.Logging\.LogVerificationBuilder') + +## LogVerificationBuilder\.AtLevelOrAbove\(LogLevel\) Method + +Restricts matches to entries logged at [level](Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).md#Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).level 'Compono\.Logging\.LogVerificationBuilder\.AtLevelOrAbove\(Microsoft\.Extensions\.Logging\.LogLevel\)\.level') or any more severe level +\(e\.g\. `AtLevelOrAbove(LogLevel.Error)` matches Error and Critical\)\. A captured entry is +never [Microsoft\.Extensions\.Logging\.LogLevel\.None](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel.none 'Microsoft\.Extensions\.Logging\.LogLevel\.None'), and neither is [Microsoft\.Extensions\.Logging\.LogLevel\.None](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel.none 'Microsoft\.Extensions\.Logging\.LogLevel\.None') ever treated as +"above" anything, so `AtLevelOrAbove(LogLevel.None)` matches nothing\. + +```csharp +public Compono.Logging.LogVerificationBuilder AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel level); +``` +#### Parameters + + + +`level` [Microsoft\.Extensions\.Logging\.LogLevel](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel 'Microsoft\.Extensions\.Logging\.LogLevel') + +#### Returns +[LogVerificationBuilder](Compono.Logging.LogVerificationBuilder.md 'Compono\.Logging\.LogVerificationBuilder') \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategory(string).md b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategory(string).md new file mode 100644 index 00000000..bbbb25e6 --- /dev/null +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.InCategory(string).md @@ -0,0 +1,25 @@ +#### [Compono\.Logging](index.md 'index') +### [Compono\.Logging](Compono.Logging.md 'Compono\.Logging').[LogVerificationBuilder](Compono.Logging.LogVerificationBuilder.md 'Compono\.Logging\.LogVerificationBuilder') + +## LogVerificationBuilder\.InCategory\(string\) Method + +Restricts matches to entries whose [Category](Compono.Logging.CapturedLogEntry.Category.md 'Compono\.Logging\.CapturedLogEntry\.Category') is exactly +[category](Compono.Logging.LogVerificationBuilder.InCategory(string).md#Compono.Logging.LogVerificationBuilder.InCategory(string).category 'Compono\.Logging\.LogVerificationBuilder\.InCategory\(string\)\.category') \(ordinal, case\-sensitive \- use [Matching\(Func<CapturedLogEntry,bool>\)](Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).md 'Compono\.Logging\.LogVerificationBuilder\.Matching\(System\.Func\\)') for a prefix +or wildcard match\)\. + +```csharp +public Compono.Logging.LogVerificationBuilder InCategory(string category); +``` +#### Parameters + + + +`category` [System\.String](https://learn.microsoft.com/en-us/dotnet/api/system.string 'System\.String') + +#### Returns +[LogVerificationBuilder](Compono.Logging.LogVerificationBuilder.md 'Compono\.Logging\.LogVerificationBuilder') + +#### Exceptions + +[System\.ArgumentNullException](https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception 'System\.ArgumentNullException') +[category](Compono.Logging.LogVerificationBuilder.InCategory(string).md#Compono.Logging.LogVerificationBuilder.InCategory(string).category 'Compono\.Logging\.LogVerificationBuilder\.InCategory\(string\)\.category') is [null](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null 'https://docs\.microsoft\.com/en\-us/dotnet/csharp/language\-reference/keywords/null')\. \ No newline at end of file diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.md b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.md index 459b584e..afeb3782 100644 --- a/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.md +++ b/docs/reference/api/Compono.Logging/Compono.Logging.LogVerificationBuilder.md @@ -20,8 +20,10 @@ Inheritance [System\.Object](https://learn.microsoft.com/en-us/dotnet/api/system | :--- | :--- | | [AtLeast\(int\)](Compono.Logging.LogVerificationBuilder.AtLeast(int).md 'Compono\.Logging\.LogVerificationBuilder\.AtLeast\(int\)') | Asserts the accumulated filters matched at least [times](Compono.Logging.LogVerificationBuilder.AtLeast(int).md#Compono.Logging.LogVerificationBuilder.AtLeast(int).times 'Compono\.Logging\.LogVerificationBuilder\.AtLeast\(int\)\.times') times\. | | [AtLevel\(LogLevel\)](Compono.Logging.LogVerificationBuilder.AtLevel(Microsoft.Extensions.Logging.LogLevel).md 'Compono\.Logging\.LogVerificationBuilder\.AtLevel\(Microsoft\.Extensions\.Logging\.LogLevel\)') | Restricts matches to entries logged at exactly [level](Compono.Logging.LogVerificationBuilder.AtLevel(Microsoft.Extensions.Logging.LogLevel).md#Compono.Logging.LogVerificationBuilder.AtLevel(Microsoft.Extensions.Logging.LogLevel).level 'Compono\.Logging\.LogVerificationBuilder\.AtLevel\(Microsoft\.Extensions\.Logging\.LogLevel\)\.level')\. | +| [AtLevelOrAbove\(LogLevel\)](Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).md 'Compono\.Logging\.LogVerificationBuilder\.AtLevelOrAbove\(Microsoft\.Extensions\.Logging\.LogLevel\)') | Restricts matches to entries logged at [level](Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).md#Compono.Logging.LogVerificationBuilder.AtLevelOrAbove(Microsoft.Extensions.Logging.LogLevel).level 'Compono\.Logging\.LogVerificationBuilder\.AtLevelOrAbove\(Microsoft\.Extensions\.Logging\.LogLevel\)\.level') or any more severe level \(e\.g\. `AtLevelOrAbove(LogLevel.Error)` matches Error and Critical\)\. A captured entry is never [Microsoft\.Extensions\.Logging\.LogLevel\.None](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel.none 'Microsoft\.Extensions\.Logging\.LogLevel\.None'), and neither is [Microsoft\.Extensions\.Logging\.LogLevel\.None](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loglevel.none 'Microsoft\.Extensions\.Logging\.LogLevel\.None') ever treated as "above" anything, so `AtLevelOrAbove(LogLevel.None)` matches nothing\. | | [AtMost\(int\)](Compono.Logging.LogVerificationBuilder.AtMost(int).md 'Compono\.Logging\.LogVerificationBuilder\.AtMost\(int\)') | Asserts the accumulated filters matched at most [times](Compono.Logging.LogVerificationBuilder.AtMost(int).md#Compono.Logging.LogVerificationBuilder.AtMost(int).times 'Compono\.Logging\.LogVerificationBuilder\.AtMost\(int\)\.times') times\. | | [Exactly\(int\)](Compono.Logging.LogVerificationBuilder.Exactly(int).md 'Compono\.Logging\.LogVerificationBuilder\.Exactly\(int\)') | Asserts the accumulated filters matched exactly [times](Compono.Logging.LogVerificationBuilder.Exactly(int).md#Compono.Logging.LogVerificationBuilder.Exactly(int).times 'Compono\.Logging\.LogVerificationBuilder\.Exactly\(int\)\.times') times\. | +| [InCategory\(string\)](Compono.Logging.LogVerificationBuilder.InCategory(string).md 'Compono\.Logging\.LogVerificationBuilder\.InCategory\(string\)') | Restricts matches to entries whose [Category](Compono.Logging.CapturedLogEntry.Category.md 'Compono\.Logging\.CapturedLogEntry\.Category') is exactly [category](Compono.Logging.LogVerificationBuilder.InCategory(string).md#Compono.Logging.LogVerificationBuilder.InCategory(string).category 'Compono\.Logging\.LogVerificationBuilder\.InCategory\(string\)\.category') \(ordinal, case\-sensitive \- use [Matching\(Func<CapturedLogEntry,bool>\)](Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).md 'Compono\.Logging\.LogVerificationBuilder\.Matching\(System\.Func\\)') for a prefix or wildcard match\)\. | | [Matching\(Func<CapturedLogEntry,bool>\)](Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).md 'Compono\.Logging\.LogVerificationBuilder\.Matching\(System\.Func\\)') | Restricts matches to entries satisfying an arbitrary [predicate](Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).md#Compono.Logging.LogVerificationBuilder.Matching(System.Func_Compono.Logging.CapturedLogEntry,bool_).predicate 'Compono\.Logging\.LogVerificationBuilder\.Matching\(System\.Func\\)\.predicate') \- the escape hatch for anything the named filters above don't cover\. | | [Never\(\)](Compono.Logging.LogVerificationBuilder.Never().md 'Compono\.Logging\.LogVerificationBuilder\.Never\(\)') | Asserts the accumulated filters never matched\. | | [Once\(\)](Compono.Logging.LogVerificationBuilder.Once().md 'Compono\.Logging\.LogVerificationBuilder\.Once\(\)') | Asserts the accumulated filters matched exactly once\. | diff --git a/docs/reference/api/Compono.Logging/Compono.Logging.md b/docs/reference/api/Compono.Logging/Compono.Logging.md index 31346cc0..b2f66460 100644 --- a/docs/reference/api/Compono.Logging/Compono.Logging.md +++ b/docs/reference/api/Compono.Logging/Compono.Logging.md @@ -6,7 +6,9 @@ | :--- | :--- | | [CapturingLogger](Compono.Logging.CapturingLogger.md 'Compono\.Logging\.CapturingLogger') | A hand\-written, reflection\-free [Microsoft\.Extensions\.Logging\.ILogger](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger 'Microsoft\.Extensions\.Logging\.ILogger') that captures every logged entry into an inspectable, thread\-safe, Compono\-native model \([CapturedLogEntry](Compono.Logging.CapturedLogEntry.md 'Compono\.Logging\.CapturedLogEntry')\) \- real scope tracking via [Microsoft\.Extensions\.Logging\.LoggerExternalScopeProvider](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.loggerexternalscopeprovider 'Microsoft\.Extensions\.Logging\.LoggerExternalScopeProvider'), structured\-property extraction, and genuine [MinimumLevel](Compono.Logging.LoggingOptions.MinimumLevel.md 'Compono\.Logging\.LoggingOptions\.MinimumLevel') filtering\. Directly, publicly constructible \- composing through [UseLogging\(this CompositionBuilder, Action<LoggingOptions>\)](Compono.Logging.CompositionBuilderExtensions.UseLogging(thisCompono.CompositionBuilder,System.Action_Compono.Logging.LoggingOptions_).md 'Compono\.Logging\.CompositionBuilderExtensions\.UseLogging\(this Compono\.CompositionBuilder, System\.Action\\)') is not required\. See docs/adr/0055\-compono\-logging\-testing\-support\-package\.md\. | | [CapturingLogger<T>](Compono.Logging.CapturingLogger_T_.md 'Compono\.Logging\.CapturingLogger\') | The generic counterpart to [CapturingLogger](Compono.Logging.CapturingLogger.md 'Compono\.Logging\.CapturingLogger') \- implemented once, works for every closed [Microsoft\.Extensions\.Logging\.ILogger<>](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger-1 'Microsoft\.Extensions\.Logging\.ILogger\`1'), no per\-[T](Compono.Logging.CapturingLogger_T_.md#Compono.Logging.CapturingLogger_T_.T 'Compono\.Logging\.CapturingLogger\\.T') generation needed for its own behavior\. Composes an internal `Compono.Logging.LogEntryCollector` directly rather than containing or delegating to a [CapturingLogger](Compono.Logging.CapturingLogger.md 'Compono\.Logging\.CapturingLogger') instance \(composition over inheritance, deliberately deviating from `LayeredCraft.StructuredLogging`'s `TestLogger : TestLogger` shape\)\. Directly, publicly constructible \- composing through [UseLogging\(this CompositionBuilder, Action<LoggingOptions>\)](Compono.Logging.CompositionBuilderExtensions.UseLogging(thisCompono.CompositionBuilder,System.Action_Compono.Logging.LoggingOptions_).md 'Compono\.Logging\.CompositionBuilderExtensions\.UseLogging\(this Compono\.CompositionBuilder, System\.Action\\)') is not required, and [LoggingFactoryRegistry](Compono.Logging.LoggingFactoryRegistry.md 'Compono\.Logging\.LoggingFactoryRegistry')'s generated activators call this exact same public constructor rather than a separate internal\-only path\. See docs/adr/0055\-compono\-logging\-testing\-support\-package\.md\. | +| [ComponoLoggingBuilderExtensions](Compono.Logging.ComponoLoggingBuilderExtensions.md 'Compono\.Logging\.ComponoLoggingBuilderExtensions') | Host integration entry point \- registers a test\-owned [LogCollector](Compono.Logging.LogCollector.md 'Compono\.Logging\.LogCollector') as a logging provider so every host logger's output lands in it\. Named to avoid any ambiguity with `Microsoft.Extensions.Logging.LoggingBuilderExtensions`\. See docs/adr/0071\-compono\-logging\-host\-wide\-log\-capture\.md\. | | [CompositionBuilderExtensions](Compono.Logging.CompositionBuilderExtensions.md 'Compono\.Logging\.CompositionBuilderExtensions') | Registers [Compono\.Logging](Compono.Logging.md 'Compono\.Logging') support into a [CompositionBuilder](../Compono/Compono.CompositionBuilder.md 'Compono\.CompositionBuilder')\. | +| [LogCollector](Compono.Logging.LogCollector.md 'Compono\.Logging\.LogCollector') | A test\-owned sink for host\-wide logging output\. Register one with [AddComponoCapture\(this ILoggingBuilder, LogCollector\)](Compono.Logging.ComponoLoggingBuilderExtensions.AddComponoCapture(thisMicrosoft.Extensions.Logging.ILoggingBuilder,Compono.Logging.LogCollector).md 'Compono\.Logging\.ComponoLoggingBuilderExtensions\.AddComponoCapture\(this Microsoft\.Extensions\.Logging\.ILoggingBuilder, Compono\.Logging\.LogCollector\)') on a host's [Microsoft\.Extensions\.Logging\.ILoggingBuilder](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.iloggingbuilder 'Microsoft\.Extensions\.Logging\.ILoggingBuilder'), then inspect it with [GetCapturedEntries\(\)](Compono.Logging.LogCollector.GetCapturedEntries().md 'Compono\.Logging\.LogCollector\.GetCapturedEntries\(\)')/[GetLastCapturedEntry\(\)](Compono.Logging.LogCollector.GetLastCapturedEntry().md 'Compono\.Logging\.LogCollector\.GetLastCapturedEntry\(\)') or verify it with [Verify\(\)](Compono.Logging.LogCollector.Verify().md 'Compono\.Logging\.LogCollector\.Verify\(\)') \- the same verification surface [LoggerTestingExtensions](Compono.Logging.LoggerTestingExtensions.md 'Compono\.Logging\.LoggerTestingExtensions') offers for a composed logger\. The collector is thread\-safe, is never disposed or reset by the host, and stays readable after the host is disposed\. See docs/adr/0071\-compono\-logging\-host\-wide\-log\-capture\.md\. | | [LoggerTestingExtensions](Compono.Logging.LoggerTestingExtensions.md 'Compono\.Logging\.LoggerTestingExtensions') | Direct inspection and fluent verification over any [Microsoft\.Extensions\.Logging\.ILogger](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger 'Microsoft\.Extensions\.Logging\.ILogger') \- no assertion framework required\. Every method here requires the [Microsoft\.Extensions\.Logging\.ILogger](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger 'Microsoft\.Extensions\.Logging\.ILogger') it's called on to actually be a [Compono\.Logging](Compono.Logging.md 'Compono\.Logging') capturing logger \(produced by [UseLogging\(this CompositionBuilder, Action<LoggingOptions>\)](Compono.Logging.CompositionBuilderExtensions.UseLogging(thisCompono.CompositionBuilder,System.Action_Compono.Logging.LoggingOptions_).md 'Compono\.Logging\.CompositionBuilderExtensions\.UseLogging\(this Compono\.CompositionBuilder, System\.Action\\)'), or directly via [CapturingLogger](Compono.Logging.CapturingLogger.md 'Compono\.Logging\.CapturingLogger')/[CapturingLogger<T>](Compono.Logging.CapturingLogger_T_.md 'Compono\.Logging\.CapturingLogger\')'s public constructors\) \- calling any of these against [Microsoft\.Extensions\.Logging\.Abstractions\.NullLogger<>](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.abstractions.nulllogger-1 'Microsoft\.Extensions\.Logging\.Abstractions\.NullLogger\`1'), an NSubstitute substitute, a `Compono.TestDoubles`\-generated double, or any other non\-Compono\.Logging [Microsoft\.Extensions\.Logging\.ILogger](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger 'Microsoft\.Extensions\.Logging\.ILogger') throws immediately, diagnostically, rather than returning an empty/default result\. See docs/adr/0055\-compono\-logging\-testing\-support\-package\.md's "Failure semantics for a non\-Compono\.Logging ILogger" section\. | | [LoggingFactoryRegistry](Compono.Logging.LoggingFactoryRegistry.md 'Compono\.Logging\.LoggingFactoryRegistry') | A [System\.Type](https://learn.microsoft.com/en-us/dotnet/api/system.type 'System\.Type')\-keyed registry of statically\-closed [CapturingLogger<T>](Compono.Logging.CapturingLogger_T_.md 'Compono\.Logging\.CapturingLogger\') activators, populated by a `[ModuleInitializer]` the shared `Compono.Generators` analyzer emits per discovered closed `ILogger` category \- never by this type itself\. `Compono.Logging` ships no analyzer/generator DLL of its own \(ADR\-0055 Amendment 3\)\. | | [LoggingOptions](Compono.Logging.LoggingOptions.md 'Compono\.Logging\.LoggingOptions') | Configuration for [UseLogging\(this CompositionBuilder, Action<LoggingOptions>\)](Compono.Logging.CompositionBuilderExtensions.UseLogging(thisCompono.CompositionBuilder,System.Action_Compono.Logging.LoggingOptions_).md 'Compono\.Logging\.CompositionBuilderExtensions\.UseLogging\(this Compono\.CompositionBuilder, System\.Action\\)') and for directly constructing a [CapturingLogger](Compono.Logging.CapturingLogger.md 'Compono\.Logging\.CapturingLogger')/[CapturingLogger<T>](Compono.Logging.CapturingLogger_T_.md 'Compono\.Logging\.CapturingLogger\')\. Fixed at construction time \- there is no runtime\-mutable equivalent, unlike `LayeredCraft.StructuredLogging`'s `TestLogger.MinimumLogLevel` setter\. See docs/adr/0055\-compono\-logging\-testing\-support\-package\.md\. | diff --git a/docs/troubleshooting/common-errors.md b/docs/troubleshooting/common-errors.md index ac3cbed5..5da164c7 100644 --- a/docs/troubleshooting/common-errors.md +++ b/docs/troubleshooting/common-errors.md @@ -292,6 +292,44 @@ and never a `CMP` code — for four distinct situations: '...', which is not a '...'.`** — the lookup returned a value of the wrong type (only possible with a non-xUnit `ITestContext` implementation). +### "`Verify()` on a host `ILogger` throws" + +A logger resolved from a host's `IServiceProvider` is the host's own +`ILogger` implementation, not a Compono capturing logger. `Verify()` and +the other `LoggerTestingExtensions` members require a logger produced by +`UseLogging()` or a directly constructed `CapturingLogger`/ +`CapturingLogger`, so they throw: + +```text +'Microsoft.Extensions.Logging.Logger<...>' is not a Compono.Logging capturing logger. ... +``` + +Host-wide capture is a **separate destination** from per-logger capture in +v1: register a `LogCollector` on the host's logging pipeline with +`AddComponoCapture()`, then call `Verify()`/`GetCapturedEntries()` on the +collector instead of on the host logger. See +[Host-wide capture](../packages/compono-logging.md#host-wide-capture-logcollector--addcomponocapture) +and [How Do I Assert Nothing Logged at Error or Above Across a Generic +Host?](../how-to/assert-nothing-logged-at-error-across-a-host.md). + +### "Debug entries are missing from `LogCollector`" + +The collector does not override the host's filter rules. A Generic Host's +default minimum level is `Information`, so `Debug` and `Trace` entries are +filtered out before they reach any provider, including Compono's. Lower the +host minimum when the test needs them: + +```csharp +builder.Logging.SetMinimumLevel(LogLevel.Trace); +``` + +The same happens when a configured category rule or `AddFilter` excludes +the category. On .NET 10 and later you can also target only the Compono +provider with the `Compono` alias, for example +`Logging:Compono:LogLevel:Default`. On .NET 8 and 9 the alias is not +available from the shipped `Logging.Abstractions` dependency (ADR-0071 +Amendment 1); use the global minimum level or `AddFilter` there instead. + ### "Two composed parameters of the same type aren't the same instance" That's the default — composition is independent per parameter unless you diff --git a/docs/troubleshooting/index.md b/docs/troubleshooting/index.md index 28e7410e..44a5a9b4 100644 --- a/docs/troubleshooting/index.md +++ b/docs/troubleshooting/index.md @@ -10,6 +10,9 @@ than reading top to bottom. - **A test throws `CompositionException`/`CompositionConfigurationException` at runtime**, with no `CMP` code → [Common Errors: Runtime Composition Failures](common-errors.md#runtime-composition-failures). +- **A `LogCollector` assertion doesn't see entries you expected** (a host + `ILogger` throws from `Verify()`, or `Debug`/`Trace` entries are + missing) → [Common Errors: Host-wide logging](common-errors.md#verify-on-a-host-iloggert-throws). - **Something works but doesn't behave the way you expected** (a value looks wrong, a substitute doesn't do what you thought, a value isn't shared) → [FAQ](faq.md). diff --git a/mkdocs.yml b/mkdocs.yml index b0822073..d561540b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -132,6 +132,7 @@ nav: - Register a Type: how-to/register-a-type.md - Use Profiles: how-to/use-profiles.md - Share a Value Across a Test: how-to/share-a-value-across-a-test.md + - Assert Nothing Logged at Error or Above Across a Host: how-to/assert-nothing-logged-at-error-across-a-host.md - Cookbook: cookbook/index.md - Samples: - Overview: samples/index.md diff --git a/skills/compono/SKILL.md b/skills/compono/SKILL.md index c6823c6c..c4900461 100644 --- a/skills/compono/SKILL.md +++ b/skills/compono/SKILL.md @@ -52,7 +52,7 @@ some packages and not others. | `true` set (check separately; its absence is the most common setup mistake, not a reason to skip loading the reference) | | `` compose via `UseLogging()`, `CapturingLogger`/`CapturingLogger`, `Verify()` available — load `references/logging.md`. Generation is on by default once the package is referenced — never suggest a manual MSBuild opt-in step | +| `` compose via `UseLogging()`, `CapturingLogger`/`CapturingLogger`, `Verify()` available; host-wide capture via `LogCollector`/`AddComponoCapture` — load `references/logging.md`. Generation is on by default once the package is referenced — never suggest a manual MSBuild opt-in step | | ``/`UseOptions()` available — load `references/options.md` | | `Composer.Create(`, `.Create<`, `.CreateMany<`, `CompositionBuilder` | `*.cs` | High | Core Compono API in active use | | `[Compose]`, `[Compose<...>]`, `[ComposeData]`, `[Shared]` | `*.cs` | High | `Compono.XunitV3`, `Compono.TUnit`, `Compono.MSTest`, or `Compono.NUnit` attributes in active use - check which package is referenced before assuming which | @@ -497,6 +497,6 @@ Load only what the Detection table says is relevant to the current task. | `references/testdoubles.md` | `Compono.TestDoubles` is referenced or `UseGeneratedTestDoubles()` is called — `UseGeneratedTestDoubles()`/generated `Configure()`/`Verify()` work, `Match` matching, `ReturnsCallback(...)`, and multiple responses for eligible members, including diagnosing a missing `ComponoGeneratedTestDoubles` opt-in | | `references/dependencyinjection.md` | `Compono.DependencyInjection` is referenced or `.AsServiceProvider()` is called — `row.AsServiceProvider()`, its stable-identity/caching contract, and what it deliberately can't resolve | | `references/http.md` | `Compono.Http` is referenced — `TestHttpHandler`/matching/verification/lifetime work | -| `references/logging.md` | `Compono.Logging` is referenced or `UseLogging()` is called — `ILogger`/`ILogger` composition, `CapturingLogger`/`CapturingLogger`, structured properties, scope semantics, `Verify()`, and the `ComponoGeneratedLogging` default-on/opt-out behavior | +| `references/logging.md` | `Compono.Logging` is referenced or `UseLogging()` is called — `ILogger`/`ILogger` composition, `CapturingLogger`/`CapturingLogger`, structured properties, scope semantics, `Verify()`, host-wide capture (`LogCollector`/`AddComponoCapture`, `Category`, `AtLevelOrAbove`/`InCategory`, host-vs-composed boundaries), and the `ComponoGeneratedLogging` default-on/opt-out behavior | | `references/options.md` | `Compono.Options` is referenced or `UseOptions(` is called — `TestOptionsSource`/`UseOptions()` identity model, named options, the unconfigured-name diagnostic, `IConfiguration`-vs-`Compono.Options` routing, and the Finding B boundary | | `references/patterns-and-antipatterns.md` | Reviewing existing Compono usage for correctness, migrating from AutoFixture, or unsure whether an approach is idiomatic | diff --git a/skills/compono/evals/evals.json b/skills/compono/evals/evals.json index ef98d672..0cad0d6b 100644 --- a/skills/compono/evals/evals.json +++ b/skills/compono/evals/evals.json @@ -754,6 +754,34 @@ "Does not try to read the fixture in a static initializer or at discovery time", "Does not pass a fixture-owned IDisposable as a theory argument (the JIT xUnit engine would dispose the fixture's instance); does not imply the concern is missing automatic cleanup" ] + }, + { + "id": 61, + "category": "activation", + "prompt": "My test starts the real app with Host.CreateApplicationBuilder and runs its startup path. I want to assert that nothing at Error or above was logged anywhere during startup, including framework categories I never composed. How do I do that with Compono.Logging?", + "expected_output": "Create a test-owned LogCollector, register it with builder.Logging.AddComponoCapture(logs) (optionally after ClearProviders), build/start the host, then assert logs.Verify().AtLevelOrAbove(LogLevel.Error).Never(). Verify on the collector, not on a composed logger - host-wide and composed capture are separate destinations in this release. The host's own filters still apply: with the default minimum Information, Debug/Trace are not captured (lower it with SetMinimumLevel/AddFilter if needed). Do not use FakeLogCollector/Microsoft.Extensions.Diagnostics.Testing, and do not propose forwarding host output into a composed logger.", + "files": [], + "expectations": [ + "Creates a LogCollector and registers it via AddComponoCapture on the host's ILoggingBuilder", + "Asserts with collector.Verify().AtLevelOrAbove(LogLevel.Error).Never() (not a composed logger's Verify())", + "Explains host and composed capture are separate destinations in this release", + "Notes the host's filter minimum still applies, so Debug/Trace need SetMinimumLevel/AddFilter to be captured", + "Does not reach for FakeLogCollector, Microsoft.Extensions.Diagnostics.Testing, or a reflection-based capture hack" + ] + }, + { + "id": 62, + "category": "behavioral-correctness", + "prompt": "Compono.Logging is referenced and UseLogging() works for my composed types, but when I resolve ILogger from host.Services and call logger.Verify(), it throws InvalidOperationException. Why, and what should I do instead?", + "expected_output": "An ILogger resolved from a real host's IServiceProvider is the host's own Logger, not a Compono CapturingLogger, so the CapturingLogger facade (and Verify()/GetCapturedEntries()) is unavailable. In this release host-wide capture and composed capture are separate: register a test-owned LogCollector with AddComponoCapture() on the host's logging builder and verify/read through the collector (e.g. logs.Verify().InCategory(...)); the exception message points there. Do not suggest UseLogging() on the host, casting/unwrapping the logger, or forwarding host output into a composed logger - none of those exist.", + "files": [], + "expectations": [ + "Explains the host-resolved ILogger is the host's Logger, not a Compono capturing logger, so Verify() cannot work on it", + "Points to LogCollector + AddComponoCapture as the host-wide capture mechanism", + "States host-wide and composed capture are separate destinations, with no forwarding in this release", + "Does not suggest registering UseLogging() on the host, casting/unwrapping the host logger, or a nonexistent forwarding option", + "Does not claim host-wide capture is unsupported" + ] } ] } diff --git a/skills/compono/references/logging.md b/skills/compono/references/logging.md index 24105cae..f357c494 100644 --- a/skills/compono/references/logging.md +++ b/skills/compono/references/logging.md @@ -3,7 +3,9 @@ Only relevant if the project references `Compono.Logging`. `UseLogging()` composes `ILogger`/`ILogger` as a hand-written `CapturingLogger`/ `CapturingLogger`, plus `CapturedLogEntry` and the fluent `Verify()` -surface. +surface. A test-owned `LogCollector` + `AddComponoCapture()` captures a +real Generic Host's *host-wide* output (every category, including +container-resolved `ILogger` and framework logging). ```csharp using Compono; @@ -38,6 +40,11 @@ currently hand-rolls a fake `ILogger`, uses `NullLogger.Instance` and therefore can't assert anything about logging, or manually `Register>(...)`s a logger for one specific type. +Also use it for host-wide assertions against a real Generic Host/ +`WebApplicationFactory` — "nothing logged at `Error` or above anywhere," +framework lifetime messages, a container-resolved `ILogger` — via +`LogCollector` + `AddComponoCapture()` (below). + ## When NOT to use it The test doesn't care about logging behavior at all — a bare @@ -100,7 +107,8 @@ discovered. `Compono.TestDoubles`/`Compono.Http`'s own `Verify()` vocabulary exactly — never suggest a two-verb `VerifyLog()...Verify()` shape, that was explicitly considered and rejected): - `.AtLevel(level)`, `.WithEventId(id)`, `.WithException()`, + `.AtLevel(level)`, `.AtLevelOrAbove(level)`, `.InCategory(category)`, + `.WithEventId(id)`, `.WithException()`, `.WithMessageContaining(text)`, `.Matching(predicate)`, ending in `.Once()` / `.Never()` / `.Exactly(n)` / `.AtLeast(n)` / `.AtMost(n)` — each a thin forward through the same shared count-verification semantics @@ -110,6 +118,51 @@ discovered. direct construction, no composition required, identical behavior to a provider-composed instance. +## Host-wide capture — `LogCollector` + `AddComponoCapture` + +Composed loggers only see Compono-composed output. For a real Generic Host +(or `WebApplicationFactory.ConfigureLogging`, or +`services.AddLogging(...)`), register a test-owned collector: + +```csharp +var logs = new LogCollector(); +var builder = Host.CreateApplicationBuilder(); +builder.Logging.ClearProviders(); +builder.Logging.AddComponoCapture(logs); +using var host = builder.Build(); + +logs.Verify().AtLevelOrAbove(LogLevel.Error).InCategory("Payments").Never(); +``` + +Key semantics to get right: + +- `Category` is on every `CapturedLogEntry`. Host entries carry the exact + `ILoggerProvider.CreateLogger` string; composed/direct `CapturingLogger` + matches `LoggerFactory.CreateLogger()`; non-generic `CapturingLogger` + and a bare composed `ILogger` carry `""`. `InCategory` is exact, ordinal, + case-sensitive — use `.Matching(...)` for prefixes. +- **Behavioral change**: `Category` participates in the record's value + equality. Entries differing only by category are not equal. This is + intentional (ADR-0071), not a bug to "fix." +- Host and composed capture are **separate destinations** in this release. + A container-resolved `ILogger` is the host's logger: calling + `Verify()`/`GetCapturedEntries()` on it still throws + `InvalidOperationException`, now pointing at `LogCollector`/ + `AddComponoCapture`. Never suggest forwarding host output into a composed + logger — it doesn't exist yet. +- The host's own filters still apply: default minimum `Information` means + `Debug`/`Trace` are not captured; lower it with + `builder.Logging.SetMinimumLevel(LogLevel.Trace)` or `AddFilter`. + `AddComponoCapture` never changes filter rules. On net10/net11 a + `Logging:Compono:LogLevel` provider-alias rule also works; on net8/net9 + it does not (ADR-0071 Amendment 1). +- The test owns the collector; the host owns the provider. Disposing the + host stops capture but never clears the collector — entries stay + readable and `ClearCapturedEntries()` still works. Registering the same + collector twice is idempotent; different collectors each receive every + entry; one collector across hosts receives all (disposing one host stops + only that host). + ## Structured properties and `MessageTemplate` `CapturedLogEntry.Properties` (`IReadOnlyList>?`) @@ -142,8 +195,11 @@ threshold is the whole v1 surface, don't invent a richer one. 1. **Non-Compono.Logging `ILogger`** — `logger.Verify()`/etc. called on an `ILogger` that isn't a `CapturingLogger`/`CapturingLogger` (`NullLogger.Instance`, an NSubstitute substitute, a - `Compono.TestDoubles` double) → `InvalidOperationException` at the - call site. Usually means registration order is backwards (below). + `Compono.TestDoubles` double, or a container-resolved host + `ILogger`) → `InvalidOperationException` at the call site. Usually + means registration order is backwards (below), or the logger came from + a host's `IServiceProvider` — then use `LogCollector`/ + `AddComponoCapture` instead. 2. **Missing generated activation at runtime** — `LoggingProvider` recognized a closed `ILogger` request but no generator-discovered activation exists for that category → a *different* @@ -218,11 +274,12 @@ belong in an ordinary composition/verification example. ## v1 boundaries — do not invent capability beyond these -No `ILoggerFactory` composition, no Serilog/provider-specific behavior, -no test-runner output capture/routing, no DI integration -(`services.AddCompono...`-style), no cross-scope structured-property -flattening/searching, no category-string constructor for the non-generic -`CapturingLogger`, no dependency on +No *composing/replacing* a host's `ILoggerFactory` (a host *provider* +capturing into a `LogCollector` via `AddComponoCapture` **is** supported), +no Serilog/provider-specific behavior, no test-runner output +capture/routing, no DI-integration package beyond `AddComponoCapture`, no +cross-scope structured-property flattening/searching, no category-string +constructor for the non-generic `CapturingLogger`, no dependency on `Microsoft.Extensions.Diagnostics.Testing`. If asked whether one of these exists, say plainly that it doesn't rather than improvising a plausible- looking API. diff --git a/src/Compono.Logging/CapturedLogEntry.cs b/src/Compono.Logging/CapturedLogEntry.cs index dd621e96..1f2f0e9c 100644 --- a/src/Compono.Logging/CapturedLogEntry.cs +++ b/src/Compono.Logging/CapturedLogEntry.cs @@ -18,6 +18,7 @@ public readonly record struct CapturedLogEntry /// constructor is rather than a public object-initializer surface. /// internal CapturedLogEntry( + string category, LogLevel logLevel, EventId eventId, Exception? exception, @@ -28,6 +29,7 @@ internal CapturedLogEntry( IReadOnlyList scopes, DateTimeOffset timestamp) { + Category = category; LogLevel = logLevel; EventId = eventId; Exception = exception; @@ -39,6 +41,16 @@ internal CapturedLogEntry( Timestamp = timestamp; } + /// + /// The logger's category - the exact string passed to + /// for a host-captured entry, or the + /// LoggerFactory.CreateLogger<T>()-equivalent name for a composed/directly + /// constructed . The non-generic + /// (and a bare ) uses the empty string. This is part of the record's + /// value equality (ADR-0071's one intentional behavioral compatibility change). + /// + public string Category { get; } + /// The level this entry was logged at. Never - a /// call is never captured in the first place. public LogLevel LogLevel { get; } diff --git a/src/Compono.Logging/CapturingLogger.cs b/src/Compono.Logging/CapturingLogger.cs index eac0c209..e6e575f4 100644 --- a/src/Compono.Logging/CapturingLogger.cs +++ b/src/Compono.Logging/CapturingLogger.cs @@ -26,7 +26,7 @@ public sealed class CapturingLogger : ILogger, ICapturingLoggerFacade /// ( minimum level). public CapturingLogger(LoggingOptions? options = null) { - _collector = new LogEntryCollector(options); + _collector = new LogEntryCollector(options, string.Empty); } /// diff --git a/src/Compono.Logging/CapturingLogger{T}.cs b/src/Compono.Logging/CapturingLogger{T}.cs index b95e6880..3334aa9e 100644 --- a/src/Compono.Logging/CapturingLogger{T}.cs +++ b/src/Compono.Logging/CapturingLogger{T}.cs @@ -25,7 +25,7 @@ public sealed class CapturingLogger : ILogger, ICapturingLoggerFacade /// ( minimum level). public CapturingLogger(LoggingOptions? options = null) { - _collector = new LogEntryCollector(options); + _collector = new LogEntryCollector(options, LoggerCategoryName.For(typeof(T))); } /// diff --git a/src/Compono.Logging/ComponoCaptureRegistration.cs b/src/Compono.Logging/ComponoCaptureRegistration.cs new file mode 100644 index 00000000..571ebed8 --- /dev/null +++ b/src/Compono.Logging/ComponoCaptureRegistration.cs @@ -0,0 +1,18 @@ +namespace Compono.Logging; + +/// +/// DI registration marker for - its +/// presence in the service collection is how a repeated registration of the same +/// is detected and made idempotent, without the distinct-collector-dropping +/// behavior a naive TryAddEnumerable (dedup by implementation type) would cause. Internal - +/// purely a registration detail. See docs/adr/0071-compono-logging-host-wide-log-capture.md. +/// +internal sealed class ComponoCaptureRegistration +{ + public ComponoCaptureRegistration(LogCollector collector) + { + Collector = collector; + } + + public LogCollector Collector { get; } +} diff --git a/src/Compono.Logging/ComponoLogCollectorLogger.cs b/src/Compono.Logging/ComponoLogCollectorLogger.cs new file mode 100644 index 00000000..08f2c721 --- /dev/null +++ b/src/Compono.Logging/ComponoLogCollectorLogger.cs @@ -0,0 +1,37 @@ +using Microsoft.Extensions.Logging; + +namespace Compono.Logging; + +/// +/// The handed out by - one per +/// CreateLogger(categoryName) call, forwarding into the provider's single shared +/// tagged with the exact category string it was created with. Internal - a +/// consumer never holds this type directly. See +/// docs/adr/0071-compono-logging-host-wide-log-capture.md. +/// +internal sealed class ComponoLogCollectorLogger : ILogger +{ + private readonly ComponoLogCollectorProvider _provider; + private readonly string _category; + + public ComponoLogCollectorLogger(ComponoLogCollectorProvider provider, string category) + { + _provider = provider; + _category = category; + } + + public IDisposable? BeginScope(TState state) + where TState : notnull => + _provider.PushScope(state); + + public bool IsEnabled(LogLevel logLevel) => + !_provider.IsDisposed && logLevel != LogLevel.None; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) => + _provider.Log(_category, logLevel, eventId, state, exception, formatter); +} diff --git a/src/Compono.Logging/ComponoLogCollectorProvider.cs b/src/Compono.Logging/ComponoLogCollectorProvider.cs new file mode 100644 index 00000000..08dcd1f8 --- /dev/null +++ b/src/Compono.Logging/ComponoLogCollectorProvider.cs @@ -0,0 +1,68 @@ +using Microsoft.Extensions.Logging; + +namespace Compono.Logging; + +/// +/// The internal behind - one instance per +/// distinct collector registered with +/// . Implements +/// so a logger's scopes come from the host's own scope provider +/// (falling back to its own only if the host never supplies +/// one). Never public - a consumer reaches capture through . See +/// docs/adr/0071-compono-logging-host-wide-log-capture.md and its Amendment 1. +/// +// ProviderAliasAttribute only lives in Logging.Abstractions on net10.0+; on net8.0/net9.0 it is in +// the Microsoft.Extensions.Logging implementation package, which ADR-0071 deliberately doesn't +// reference. ADR-0071 Amendment 1 therefore scopes the alias (and the Logging:Compono:* config rule +// it enables) to net10.0/net11.0 so the shipped dependency graph stays Abstractions-only. +#if NET10_0_OR_GREATER +[ProviderAlias("Compono")] +#endif +internal sealed class ComponoLogCollectorProvider : ILoggerProvider, ISupportExternalScope +{ + private readonly LogCollector _collector; + private readonly LoggerExternalScopeProvider _fallbackScopeProvider = new(); + private IExternalScopeProvider? _scopeProvider; + private volatile bool _disposed; + + public ComponoLogCollectorProvider(LogCollector collector) + { + _collector = collector; + } + + /// Observable seam for tests - once ran. + internal bool IsDisposed => _disposed; + + public ILogger CreateLogger(string categoryName) => new ComponoLogCollectorLogger(this, categoryName); + + public void SetScopeProvider(IExternalScopeProvider scopeProvider) + { + ArgumentNullException.ThrowIfNull(scopeProvider); + + _scopeProvider = scopeProvider; + } + + public void Dispose() => _disposed = true; + + internal IDisposable PushScope(TState state) + where TState : notnull => + (_scopeProvider ?? _fallbackScopeProvider).Push(state); + + internal void Log( + string category, + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) + { + // A racing log against a concurrently-disposed provider may be captured or dropped, but it + // must never throw or corrupt the collector (ADR-0071 disposal semantics). + if (_disposed || logLevel == LogLevel.None) + return; + + var scopes = LogEntryFactory.SnapshotScopes(_scopeProvider ?? _fallbackScopeProvider); + var entry = LogEntryFactory.Create(category, logLevel, eventId, state, exception, formatter, scopes); + _collector.Add(entry); + } +} diff --git a/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs b/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs new file mode 100644 index 00000000..169e6904 --- /dev/null +++ b/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs @@ -0,0 +1,52 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Compono.Logging; + +/// +/// Host integration entry point - registers a test-owned as a logging +/// provider so every host logger's output lands in it. Named to avoid any ambiguity with +/// Microsoft.Extensions.Logging.LoggingBuilderExtensions. See +/// docs/adr/0071-compono-logging-host-wide-log-capture.md. +/// +public static class ComponoLoggingBuilderExtensions +{ + /// + /// Registers as a Compono logging provider on + /// . Every host logger's entries are then appended to the collector + /// (subject to the host's own filter rules) and inspectable via + /// /. This never + /// changes filter rules. Registering the same collector twice is idempotent (one provider, no + /// duplicate entries); registering distinct collectors adds one provider per collector, and each + /// receives every entry. Returns for chaining. + /// + /// or + /// is . + public static ILoggingBuilder AddComponoCapture(this ILoggingBuilder builder, LogCollector collector) + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(collector); + + if (IsAlreadyRegistered(builder.Services, collector)) + return builder; + + builder.Services.Add(ServiceDescriptor.Singleton(new ComponoCaptureRegistration(collector))); + builder.Services.Add(ServiceDescriptor.Singleton(_ => new ComponoLogCollectorProvider(collector))); + return builder; + } + + private static bool IsAlreadyRegistered(IServiceCollection services, LogCollector collector) + { + foreach (var descriptor in services) + { + if (descriptor.ServiceType == typeof(ComponoCaptureRegistration) + && descriptor.ImplementationInstance is ComponoCaptureRegistration registration + && ReferenceEquals(registration.Collector, collector)) + { + return true; + } + } + + return false; + } +} diff --git a/src/Compono.Logging/ILogEntrySource.cs b/src/Compono.Logging/ILogEntrySource.cs new file mode 100644 index 00000000..fd719724 --- /dev/null +++ b/src/Compono.Logging/ILogEntrySource.cs @@ -0,0 +1,11 @@ +namespace Compono.Logging; + +/// +/// The entry source filters over - implemented by the composed +/// and by the public host-wide , so both +/// verification surfaces share one implementation. Internal - never part of the public API. +/// +internal interface ILogEntrySource +{ + IReadOnlyList GetEntries(); +} diff --git a/src/Compono.Logging/LogCollector.cs b/src/Compono.Logging/LogCollector.cs new file mode 100644 index 00000000..fc566ce0 --- /dev/null +++ b/src/Compono.Logging/LogCollector.cs @@ -0,0 +1,70 @@ +namespace Compono.Logging; + +/// +/// A test-owned sink for host-wide logging output. Register one with +/// on a host's +/// , then inspect it with +/// / or verify it with +/// - the same verification surface offers +/// for a composed logger. The collector is thread-safe, is never disposed or reset by the host, and +/// stays readable after the host is disposed. See +/// docs/adr/0071-compono-logging-host-wide-log-capture.md. +/// +public sealed class LogCollector : ILogEntrySource +{ + // A plain object lock, not System.Threading.Lock - this project multi-targets net8.0, which + // predates that type (introduced in .NET 9). + private readonly object _lock = new(); + private readonly List _entries = []; + + /// Creates an empty, test-owned collector. + public LogCollector() + { + } + + /// Every entry captured so far, oldest first - a snapshot, safe to read while logging + /// continues on other threads. + public IReadOnlyList GetCapturedEntries() + { + lock (_lock) + { + return [.. _entries]; + } + } + + /// The most recently captured entry, or if nothing has been + /// captured yet. + public CapturedLogEntry? GetLastCapturedEntry() + { + lock (_lock) + { + return _entries.Count == 0 ? null : _entries[^1]; + } + } + + /// Discards every entry captured so far. The collector stays fully usable afterward - + /// clearing never detaches it from a host that is still capturing into it. + public void ClearCapturedEntries() + { + lock (_lock) + { + _entries.Clear(); + } + } + + /// + /// The entry point for fluent verification over this collector's entries, e.g. + /// logs.Verify().AtLevelOrAbove(LogLevel.Error).Never(). + /// + public LogVerificationBuilder Verify() => new(this); + + IReadOnlyList ILogEntrySource.GetEntries() => GetCapturedEntries(); + + internal void Add(CapturedLogEntry entry) + { + lock (_lock) + { + _entries.Add(entry); + } + } +} diff --git a/src/Compono.Logging/LogEntryCollector.cs b/src/Compono.Logging/LogEntryCollector.cs index cfaf4867..daa4331f 100644 --- a/src/Compono.Logging/LogEntryCollector.cs +++ b/src/Compono.Logging/LogEntryCollector.cs @@ -4,12 +4,14 @@ namespace Compono.Logging; /// /// Owns the actual capture state behind one / -/// instance - a lock-guarded entry list, one , and the -/// effective fixed at construction. Internal - never -/// referenced directly by a consumer; reached only through the two public logger types and -/// . See docs/adr/0055-compono-logging-testing-support-package.md. +/// instance - a lock-guarded entry list and one , with the +/// effective fixed at construction and the category computed +/// once. Internal - never referenced directly by a consumer; reached only through the two public logger +/// types and . See +/// docs/adr/0055-compono-logging-testing-support-package.md and +/// docs/adr/0071-compono-logging-host-wide-log-capture.md. /// -internal sealed class LogEntryCollector +internal sealed class LogEntryCollector : ILogEntrySource { // A plain object lock, not System.Threading.Lock - this project multi-targets net8.0, which // predates that type (introduced in .NET 9). @@ -17,10 +19,12 @@ internal sealed class LogEntryCollector private readonly List _entries = []; private readonly LoggerExternalScopeProvider _scopeProvider = new(); private readonly LogLevel _minimumLevel; + private readonly string _category; - public LogEntryCollector(LoggingOptions? options) + public LogEntryCollector(LoggingOptions? options, string category) { _minimumLevel = (options ?? new LoggingOptions()).MinimumLevel; + _category = category; } /// @@ -47,20 +51,8 @@ public void Record( if (!IsEnabled(logLevel)) return; - var message = formatter(state, exception); - var (properties, messageTemplate) = ExtractStructuredState(state); - var scopes = SnapshotScopes(); - - var entry = new CapturedLogEntry( - logLevel, - eventId, - exception, - message, - state, - properties, - messageTemplate, - scopes, - DateTimeOffset.UtcNow); + var scopes = LogEntryFactory.SnapshotScopes(_scopeProvider); + var entry = LogEntryFactory.Create(_category, logLevel, eventId, state, exception, formatter, scopes); lock (_lock) { @@ -95,36 +87,4 @@ public void Clear() _entries.Clear(); } } - - // Reflection-free: a single pattern match against the interface both the compiler-generated - // FormattedLogValues (an ordinary LogInformation(...) call) and the shared LoggerMessageState - // (every [LoggerMessage] source-generated call site) satisfy identically - confirmed empirically - // during RESEARCH-0013's pre-ADR validation spike, no special-casing needed for either style. - private static (IReadOnlyList>? Properties, string? MessageTemplate) ExtractStructuredState(TState state) - { - if (state is not IReadOnlyList> pairs) - return (null, null); - - var properties = new KeyValuePair[pairs.Count]; - string? messageTemplate = null; - for (var i = 0; i < pairs.Count; i++) - { - var pair = pairs[i]; - properties[i] = new KeyValuePair(pair.Key, pair.Value); - if (pair.Key == "{OriginalFormat}") - messageTemplate = pair.Value as string; - } - - return (properties, messageTemplate); - } - - private object[] SnapshotScopes() - { - var scopes = new List(); - // ForEachScope's callback parameter is annotated `object?` even though a real scope value can - // never actually be null (BeginScope requires `TState : notnull`) - the null-forgiving - // operator here reflects that guarantee, not a genuine possible-null case. - _scopeProvider.ForEachScope(static (scope, state) => state.Add(scope!), scopes); - return [.. scopes]; - } } diff --git a/src/Compono.Logging/LogEntryFactory.cs b/src/Compono.Logging/LogEntryFactory.cs new file mode 100644 index 00000000..0707caa5 --- /dev/null +++ b/src/Compono.Logging/LogEntryFactory.cs @@ -0,0 +1,69 @@ +using Microsoft.Extensions.Logging; + +namespace Compono.Logging; + +/// +/// The single, shared construction path for every - both the composed +/// path and the host path +/// call this, so structured-state extraction, message formatting, scope snapshots, and timestamps can +/// never drift between the two (ADR-0071). Internal and reflection-free. +/// +internal static class LogEntryFactory +{ + public static CapturedLogEntry Create( + string category, + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter, + IReadOnlyList scopes) + { + var message = formatter(state, exception); + var (properties, messageTemplate) = ExtractStructuredState(state); + + return new CapturedLogEntry( + category, + logLevel, + eventId, + exception, + message, + state, + properties, + messageTemplate, + scopes, + DateTimeOffset.UtcNow); + } + + public static IReadOnlyList SnapshotScopes(IExternalScopeProvider scopeProvider) + { + var scopes = new List(); + // ForEachScope's callback parameter is annotated `object?` even though a real scope value can + // never actually be null (BeginScope requires `TState : notnull`) - the + // null-forgiving operator here reflects that guarantee, not a genuine possible-null case. + scopeProvider.ForEachScope(static (scope, state) => state.Add(scope!), scopes); + return [.. scopes]; + } + + // Reflection-free: a single pattern match against the interface both the compiler-generated + // FormattedLogValues (an ordinary LogInformation(...) call) and the shared LoggerMessageState + // (every [LoggerMessage] source-generated call site) satisfy identically - confirmed empirically + // during RESEARCH-0013's pre-ADR validation spike, no special-casing needed for either style. + private static (IReadOnlyList>? Properties, string? MessageTemplate) ExtractStructuredState(TState state) + { + if (state is not IReadOnlyList> pairs) + return (null, null); + + var properties = new KeyValuePair[pairs.Count]; + string? messageTemplate = null; + for (var i = 0; i < pairs.Count; i++) + { + var pair = pairs[i]; + properties[i] = new KeyValuePair(pair.Key, pair.Value); + if (pair.Key == "{OriginalFormat}") + messageTemplate = pair.Value as string; + } + + return (properties, messageTemplate); + } +} diff --git a/src/Compono.Logging/LogVerificationBuilder.cs b/src/Compono.Logging/LogVerificationBuilder.cs index 1bd14de5..fa583e9d 100644 --- a/src/Compono.Logging/LogVerificationBuilder.cs +++ b/src/Compono.Logging/LogVerificationBuilder.cs @@ -13,18 +13,40 @@ namespace Compono.Logging; /// public sealed class LogVerificationBuilder { - private readonly LogEntryCollector _collector; + private readonly ILogEntrySource _entrySource; private readonly List<(string Description, Func Predicate)> _filters = []; - internal LogVerificationBuilder(LogEntryCollector collector) + internal LogVerificationBuilder(ILogEntrySource entrySource) { - _collector = collector; + _entrySource = entrySource; } /// Restricts matches to entries logged at exactly . public LogVerificationBuilder AtLevel(LogLevel level) => Add($"level {level}", entry => entry.LogLevel == level); + /// + /// Restricts matches to entries logged at or any more severe level + /// (e.g. AtLevelOrAbove(LogLevel.Error) matches Error and Critical). A captured entry is + /// never , and neither is ever treated as + /// "above" anything, so AtLevelOrAbove(LogLevel.None) matches nothing. + /// + public LogVerificationBuilder AtLevelOrAbove(LogLevel level) => + Add($"level {level} or above", entry => entry.LogLevel != LogLevel.None && entry.LogLevel >= level); + + /// + /// Restricts matches to entries whose is exactly + /// (ordinal, case-sensitive - use for a prefix + /// or wildcard match). + /// + /// is . + public LogVerificationBuilder InCategory(string category) + { + ArgumentNullException.ThrowIfNull(category); + + return Add($"category \"{category}\"", entry => string.Equals(entry.Category, category, StringComparison.Ordinal)); + } + /// Restricts matches to entries logged with exactly . public LogVerificationBuilder WithEventId(EventId eventId) => Add($"event id {eventId}", entry => entry.EventId == eventId); @@ -75,7 +97,7 @@ private LogVerificationBuilder Add(string description, Func +/// Computes the category name LoggerFactory.CreateLogger<T>() would use, using only +/// trim-safe name properties (no reflection over members, no +/// MakeGenericType). Mirrors the BCL's internal TypeNameHelper.GetTypeDisplayName +/// call with its logging parameters (includeGenericParameters: false, +/// nestedTypeDelimiter: '.', fullName: true): a full namespace-qualified name, nested +/// types joined with '.', generic arity and arguments removed, and C# keyword aliases for +/// built-in types. Internal - computed once per instance. +/// +internal static class LoggerCategoryName +{ + private static readonly Dictionary BuiltInTypeNames = new() + { + [typeof(void)] = "void", + [typeof(bool)] = "bool", + [typeof(byte)] = "byte", + [typeof(char)] = "char", + [typeof(decimal)] = "decimal", + [typeof(double)] = "double", + [typeof(float)] = "float", + [typeof(int)] = "int", + [typeof(long)] = "long", + [typeof(object)] = "object", + [typeof(sbyte)] = "sbyte", + [typeof(short)] = "short", + [typeof(string)] = "string", + [typeof(uint)] = "uint", + [typeof(ulong)] = "ulong", + [typeof(ushort)] = "ushort", + }; + + public static string For(Type type) + { + var builder = new StringBuilder(); + AppendType(builder, type); + return builder.ToString(); + } + + private static void AppendType(StringBuilder builder, Type type) + { + if (type.IsGenericType) + { + AppendGenericType(builder, type); + } + else if (type.IsArray) + { + AppendArrayType(builder, type); + } + else if (BuiltInTypeNames.TryGetValue(type, out var builtInName)) + { + builder.Append(builtInName); + } + else + { + builder.Append(type.FullName!.Replace('+', '.')); + } + } + + private static void AppendArrayType(StringBuilder builder, Type type) + { + var elementType = type; + while (elementType.IsArray) + elementType = elementType.GetElementType()!; + + AppendType(builder, elementType); + + while (type.IsArray) + { + builder.Append('['); + builder.Append(',', type.GetArrayRank() - 1); + builder.Append(']'); + type = type.GetElementType()!; + } + } + + private static void AppendGenericType(StringBuilder builder, Type type) + { + if (type.IsNested) + { + AppendType(builder, type.DeclaringType!); + builder.Append('.'); + } + else if (!string.IsNullOrEmpty(type.Namespace)) + { + builder.Append(type.Namespace); + builder.Append('.'); + } + + var name = type.Name; + var genericPartIndex = name.IndexOf('`'); + builder.Append(genericPartIndex <= 0 ? name : name[..genericPartIndex]); + } +} diff --git a/src/Compono.Logging/LoggerTestingExtensions.cs b/src/Compono.Logging/LoggerTestingExtensions.cs index 19fd3e9d..30942809 100644 --- a/src/Compono.Logging/LoggerTestingExtensions.cs +++ b/src/Compono.Logging/LoggerTestingExtensions.cs @@ -61,6 +61,9 @@ private static ICapturingLoggerFacade RequireFacade(ILogger logger) "wins for a given request. (UseGeneratedTestDoubles() ordering is not the cause: when " + "ComponoGeneratedLogging is enabled, ILogger/ILogger are excluded from " + "Compono.TestDoubles generation entirely, so it has no generated double to offer for " + - "these types regardless of order.)"); + "these types regardless of order.) If this ILogger came from a host's IServiceProvider " + + "(for example a container-resolved ILogger), capture host-wide output with a " + + "LogCollector registered via AddComponoCapture() and call Verify()/GetCapturedEntries() " + + "on the collector instead."); } } diff --git a/test/Compono.Logging.AotSmokeTest/Compono.Logging.AotSmokeTest.csproj b/test/Compono.Logging.AotSmokeTest/Compono.Logging.AotSmokeTest.csproj index 672aa6b3..d5abe542 100644 --- a/test/Compono.Logging.AotSmokeTest/Compono.Logging.AotSmokeTest.csproj +++ b/test/Compono.Logging.AotSmokeTest/Compono.Logging.AotSmokeTest.csproj @@ -5,7 +5,8 @@ choice below): a real Native AOT publish-and-run proof through the actual packaged Compono/Compono.Logging dependency chain - composing a real ILogger constructor dependency via UseLogging(), through the shared Compono.Generators-emitted activation (not - direct construction alone), then verifying capture/Verify() work post-publish. --> + direct construction alone), then verifying capture/Verify() work post-publish, plus real + Generic Host AddComponoCapture/LogCollector host-wide capture and category parity. --> Exe + + diff --git a/test/Compono.Logging.AotSmokeTest/Program.cs b/test/Compono.Logging.AotSmokeTest/Program.cs index 84d53424..e53de28e 100644 --- a/test/Compono.Logging.AotSmokeTest/Program.cs +++ b/test/Compono.Logging.AotSmokeTest/Program.cs @@ -1,5 +1,7 @@ using Compono; using Compono.Logging; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Compono.Logging.AotSmokeTest; @@ -48,10 +50,14 @@ private static int Main() if (direct.GetCapturedEntries().Count != 1) throw new InvalidOperationException("Expected direct construction to capture independently."); + VerifyHostWideCapture(); + VerifyCategoryParityUnderAot(); + Console.WriteLine( "PASS: UseLogging()-composed ILogger (generator-discovered activation), " + - "structured-property capture, Verify(), and direct CapturingLogger construction " + - "all survived Native AOT through the packaged Compono.Logging dependency chain."); + "structured-property capture, Verify(), direct CapturingLogger construction, and " + + "Generic Host AddComponoCapture/LogCollector host-wide capture all survived Native AOT " + + "through the packaged Compono.Logging dependency chain."); return 0; } catch (Exception ex) @@ -60,4 +66,60 @@ private static int Main() return 1; } } + + private static void VerifyHostWideCapture() + { + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + using var host = builder.Build(); + var logger = host.Services.GetRequiredService().CreateLogger("Host.Smoke"); + + using (logger.BeginScope("SmokeScope")) + logger.LogWarning("host-wide {OrderId}", 42); + + if (collector.GetCapturedEntries().Count != 1) + throw new InvalidOperationException($"Expected exactly 1 host-captured entry, got {collector.GetCapturedEntries().Count}."); + + + var entry = collector.GetLastCapturedEntry()!.Value; + if (entry.Category != "Host.Smoke") + throw new InvalidOperationException($"Expected Host.Smoke category, got '{entry.Category}'."); + + if (entry.LogLevel != LogLevel.Warning) + throw new InvalidOperationException($"Expected Warning, got {entry.LogLevel}."); + + if (entry.Properties is null || entry.Properties[0].Value is not int orderId || orderId != 42) + throw new InvalidOperationException("Expected a structured OrderId property with value 42."); + + if (entry.Scopes.Count != 1 || !Equals(entry.Scopes[0], "SmokeScope")) + throw new InvalidOperationException("Expected the host-captured entry to carry its scope."); + + collector.Verify().InCategory("Host.Smoke").AtLevelOrAbove(LogLevel.Warning).Once(); + collector.Verify().AtLevelOrAbove(LogLevel.Error).Never(); + } + + private static void VerifyCategoryParityUnderAot() + { + // Compare against the real LoggerFactory's own category, never a hard-coded string - this + // proves LoggerCategoryName's trim-safe naming matches the BCL under Native AOT. + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + using var host = builder.Build(); + var factory = host.Services.GetRequiredService(); + + factory.CreateLogger().LogInformation("factory category"); + var factoryCategory = collector.GetLastCapturedEntry()!.Value.Category; + + var direct = new CapturingLogger(); + direct.LogInformation("direct category"); + var directCategory = direct.GetCapturedEntries()[0].Category; + + if (!string.Equals(factoryCategory, directCategory, StringComparison.Ordinal)) + throw new InvalidOperationException( + $"Category parity failed: factory '{factoryCategory}' vs direct '{directCategory}'."); + } } diff --git a/test/Compono.Logging.Tests/CategoryTests.cs b/test/Compono.Logging.Tests/CategoryTests.cs new file mode 100644 index 00000000..620cd4c5 --- /dev/null +++ b/test/Compono.Logging.Tests/CategoryTests.cs @@ -0,0 +1,150 @@ +using Microsoft.Extensions.Logging; + +namespace Compono.Logging.Tests; + +public sealed class CategoryTests +{ + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForPlainNamespacedType() + { + AssertCategoryMatchesFactory(); + } + + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForNestedType() + { + AssertCategoryMatchesFactory(); + } + + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForNestedTypeInNestedType() + { + AssertCategoryMatchesFactory(); + } + + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForClosedGenericType() + { + AssertCategoryMatchesFactory>(); + } + + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForNestedTypeInClosedGenericType() + { + AssertCategoryMatchesFactory.NestedCategoryType>(); + } + + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForFrameworkGenericType() + { + AssertCategoryMatchesFactory>(); + } + + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForGlobalNamespaceType() + { + AssertCategoryMatchesFactory(); + } + + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForBuiltInTypes() + { + AssertCategoryMatchesFactory(); + AssertCategoryMatchesFactory(); + AssertCategoryMatchesFactory(); + AssertCategoryMatchesFactory(); + } + + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForArrayType() + { + AssertCategoryMatchesFactory(); + } + + [Fact] + public void ComposedGenericLogger_CategoryMatchesLoggerFactory() + { + var expected = TestCategoryProbe.For(); + var composer = Composer.Create(builder => builder.UseLogging()); + + var service = composer.Create(); + service.PlaceOrder(42); + + var entry = service.Logger.GetLastCapturedEntry()!.Value; + entry.Category.Should().Be(expected); + } + + [Fact] + public void BareCapturingLogger_CategoryIsEmpty() + { + var logger = new CapturingLogger(); + + logger.LogInformation("captured"); + + logger.GetCapturedEntries()[0].Category.Should().BeEmpty(); + } + + [Fact] + public void ComposedBareILogger_CategoryIsEmpty() + { + var composer = Composer.Create(builder => builder.UseLogging()); + + var logger = composer.Create(); + logger.LogInformation("captured"); + + logger.GetCapturedEntries()[0].Category.Should().BeEmpty(); + } + + [Fact] + public void Equality_IncludesCategory_IntentionalBehavioralChangeFromAdr0071() + { + // ADR-0071 deliberately makes Category part of CapturedLogEntry's record value equality: + // otherwise two entries that differ only in which logger produced them would compare equal. + // This pins that decision so a future "fix" cannot quietly drop Category from equality. + var timestamp = new DateTimeOffset(2026, 11, 11, 12, 0, 0, TimeSpan.Zero); + + var first = new CapturedLogEntry( + "Category.A", LogLevel.Information, default, null, "same", null, null, null, [], timestamp); + var second = new CapturedLogEntry( + "Category.B", LogLevel.Information, default, null, "same", null, null, null, [], timestamp); + var third = new CapturedLogEntry( + "Category.A", LogLevel.Information, default, null, "same", null, null, null, [], timestamp); + + first.Equals(second).Should().BeFalse(); + (first == second).Should().BeFalse(); + (first != second).Should().BeTrue(); + + first.Equals(third).Should().BeTrue(); + (first == third).Should().BeTrue(); + first.GetHashCode().Should().Be(third.GetHashCode()); + } + + private static void AssertCategoryMatchesFactory() + { + var expected = TestCategoryProbe.For(); + + var logger = new CapturingLogger(); + logger.LogInformation("captured"); + + var entries = logger.GetCapturedEntries(); + entries.Should().ContainSingle(); + entries[0].Category.Should().Be(expected); + } +} + +public sealed class PlainCategoryType; + +public sealed class OuterCategoryType +{ + public sealed class InnerCategoryType + { + public sealed class DeepestCategoryType; + } +} + +public sealed class GenericCategoryType; + +public sealed class GenericOuterCategoryType +{ + public sealed class NestedCategoryType; +} diff --git a/test/Compono.Logging.Tests/Compono.Logging.Tests.csproj b/test/Compono.Logging.Tests/Compono.Logging.Tests.csproj index 2b0560cd..c660c7a0 100644 --- a/test/Compono.Logging.Tests/Compono.Logging.Tests.csproj +++ b/test/Compono.Logging.Tests/Compono.Logging.Tests.csproj @@ -42,7 +42,11 @@ - + + diff --git a/test/Compono.Logging.Tests/GlobalCategoryType.cs b/test/Compono.Logging.Tests/GlobalCategoryType.cs new file mode 100644 index 00000000..bdaab727 --- /dev/null +++ b/test/Compono.Logging.Tests/GlobalCategoryType.cs @@ -0,0 +1,3 @@ +// Intentionally declared outside any namespace: proves category naming for a global-namespace +// type matches LoggerFactory.CreateLogger() exactly. +public sealed class GlobalCategoryType; diff --git a/test/Compono.Logging.Tests/HostLogCaptureTests.cs b/test/Compono.Logging.Tests/HostLogCaptureTests.cs new file mode 100644 index 00000000..2e743fa8 --- /dev/null +++ b/test/Compono.Logging.Tests/HostLogCaptureTests.cs @@ -0,0 +1,413 @@ +using System.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Compono.Logging.Tests; + +public sealed class HostLogCaptureTests +{ + [Fact] + public void LoggerFactoryCreateLogger_CapturesTheExactCategory() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Arbitrary.Category"); + + logger.LogInformation("hello"); + + var entry = collector.GetLastCapturedEntry()!.Value; + entry.Category.Should().Be("Arbitrary.Category"); + } + + [Fact] + public void ContainerResolvedLoggerOfT_CategoryMatchesLoggerFactory() + { + var expected = TestCategoryProbe.For(); + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService>(); + + logger.LogWarning("composed category"); + + collector.GetLastCapturedEntry()!.Value.Category.Should().Be(expected); + } + + [Fact] + public async Task HostLifetime_StartAndStopEntriesAreCaptured() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + + await host.StartAsync(TestContext.Current.CancellationToken); + await host.StopAsync(TestContext.Current.CancellationToken); + + var entries = collector.GetCapturedEntries(); + entries.Should().Contain(entry => entry.Category == "Microsoft.Hosting.Lifetime"); + entries.Should().Contain(entry => entry.Message.Contains("Application started", StringComparison.Ordinal)); + entries.Should().Contain(entry => entry.Message.Contains("Application is shutting down", StringComparison.Ordinal)); + } + + [Fact] + public void VerifyAtLevelOrAboveError_Never_PassesForAHostThatLoggedNothingFailed() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Clean.Host"); + + logger.LogInformation("all good"); + + collector.Verify().AtLevelOrAbove(LogLevel.Error).Never(); + } + + [Fact] + public void VerifyAtLevelOrAboveError_Never_FailsReadablyWhenAHostLoggedError() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Never.Composed.Category"); + + logger.LogError("payment declined"); + + var act = () => collector.Verify().AtLevelOrAbove(LogLevel.Error).Never(); + + act.Should().Throw() + .WithMessage("*level Error or above*received 1*"); + } + + [Fact] + public void OrdinaryLogCall_CapturesEveryEntryField() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Fields.Category"); + var exception = new InvalidOperationException("boom"); + var eventId = new EventId(17, "OrderFailed"); + + logger.Log(LogLevel.Error, eventId, exception, "failed {Code}", 7); + + var entry = collector.GetLastCapturedEntry()!.Value; + entry.Category.Should().Be("Fields.Category"); + entry.LogLevel.Should().Be(LogLevel.Error); + entry.EventId.Should().Be(eventId); + entry.Message.Should().Be("failed 7"); + entry.Exception.Should().BeSameAs(exception); + entry.State.Should().NotBeNull(); + entry.Properties.Should().NotBeNull(); + entry.Properties!.Should().Contain(pair => pair.Key == "Code" && Equals(pair.Value, 7)); + entry.Properties!.Should().Contain(pair => pair.Key == "{OriginalFormat}" && Equals(pair.Value, "failed {Code}")); + entry.MessageTemplate.Should().Be("failed {Code}"); + entry.Scopes.Should().BeEmpty(); + entry.Timestamp.Should().BeCloseTo(DateTimeOffset.UtcNow, TimeSpan.FromMinutes(1)); + } + + [Fact] + public void CustomStateAndFormatter_ArePassedThroughUnchanged() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Fields.Category"); + var exception = new InvalidOperationException("boom"); + + logger.Log( + LogLevel.Error, + new EventId(3), + "plain state", + exception, + static (state, ex) => $"custom:{state}:{ex?.Message}"); + + var entry = collector.GetLastCapturedEntry()!.Value; + entry.Message.Should().Be("custom:plain state:boom"); + entry.State.Should().Be("plain state"); + entry.Exception.Should().BeSameAs(exception); + entry.Properties.Should().BeNull(); + entry.MessageTemplate.Should().BeNull(); + } + + [Fact] + public void LoggerMessageSourceGenerated_CapturesEveryEntryField() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Generated.Category"); + + GeneratedLogMessages.OrderPlaced(logger, 7); + + var entry = collector.GetLastCapturedEntry()!.Value; + entry.Category.Should().Be("Generated.Category"); + entry.LogLevel.Should().Be(LogLevel.Information); + entry.Message.Should().Be("Order 7 placed"); + entry.Properties.Should().NotBeNull(); + entry.Properties!.Should().Contain(pair => pair.Key == "OrderId" && Equals(pair.Value, 7)); + entry.MessageTemplate.Should().Be("Order {OrderId} placed"); + } + + [Fact] + public void ExceptionWithoutMessageArguments_IsCapturedByReference() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Exception.Category"); + var exception = new AggregateException(new InvalidOperationException("boom")); + + logger.LogError(exception, "failure with no message arguments"); + + var entry = collector.GetLastCapturedEntry()!.Value; + entry.Exception.Should().BeSameAs(exception); + entry.Message.Should().Be("failure with no message arguments"); + } + + [Fact] + public void DefaultHostMinimumLevel_ExcludesDebugAndTrace() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Filtered.Category"); + + logger.LogTrace("trace"); + logger.LogDebug("debug"); + logger.LogInformation("information"); + + var entries = collector.GetCapturedEntries(); + entries.Should().ContainSingle(); + entries[0].LogLevel.Should().Be(LogLevel.Information); + } + + [Fact] + public void SetMinimumLevelTrace_IncludesDebugAndTrace() + { + var collector = new LogCollector(); + using var host = CreateHost(collector, builder => builder.Logging.SetMinimumLevel(LogLevel.Trace)); + var logger = host.Services.GetRequiredService().CreateLogger("Filtered.Category"); + + logger.LogTrace("trace"); + logger.LogDebug("debug"); + logger.LogInformation("information"); + + collector.GetCapturedEntries().Should().HaveCount(3); + } + + [Fact] + public void HostCategoryFilter_ExcludesFilteredEntries() + { + var collector = new LogCollector(); + using var host = CreateHost(collector, builder => builder.Logging.AddFilter("Filtered.Category", LogLevel.Warning)); + var factory = host.Services.GetRequiredService(); + + factory.CreateLogger("Filtered.Category").LogInformation("excluded"); + factory.CreateLogger("Filtered.Category").LogWarning("included"); + factory.CreateLogger("Other.Category").LogInformation("other category is unaffected"); + + var entries = collector.GetCapturedEntries(); + entries.Should().Contain(entry => entry.Message == "included"); + entries.Should().Contain(entry => entry.Message == "other category is unaffected"); + entries.Should().NotContain(entry => entry.Message == "excluded"); + } + +#if NET10_0_OR_GREATER + [Fact] + public void ProviderAliasConfiguration_TargetsOnlyTheComponoProvider() + { + // ADR-0071 Amendment 1: [ProviderAlias("Compono")] lives in Logging.Abstractions only on + // net10.0+, so this provider-specific configuration rule is a net10/net11 capability; net8 + // and net9 use the global minimum level/AddFilter rules exercised above. + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Configuration["Logging:Compono:LogLevel:Default"] = "Warning"; + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + using var host = builder.Build(); + var factory = host.Services.GetRequiredService(); + + factory.CreateLogger("Alias.Category").LogInformation("below alias minimum"); + factory.CreateLogger("Alias.Category").LogWarning("meets alias minimum"); + + var entries = collector.GetCapturedEntries(); + entries.Should().ContainSingle(); + entries[0].Message.Should().Be("meets alias minimum"); + } +#endif + + [Fact] + public void LogLevelNone_IsNeverCaptured() + { + var collector = new LogCollector(); + using var host = CreateHost(collector, builder => builder.Logging.SetMinimumLevel(LogLevel.Trace)); + var logger = host.Services.GetRequiredService().CreateLogger("None.Category"); + + logger.Log(LogLevel.None, new EventId(1), "none", null, static (state, _) => state); + + collector.GetCapturedEntries().Should().BeEmpty(); + } + + [Fact] + public void ServicesAddLogging_CanRegisterComponoCapture() + { + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Services.AddLogging(logging => logging.AddComponoCapture(collector)); + using var host = builder.Build(); + + host.Services.GetRequiredService().CreateLogger("Services.Category").LogInformation("captured"); + + collector.GetLastCapturedEntry()!.Value.Category.Should().Be("Services.Category"); + } + + [Fact] + public void AddComponoCapture_NullArguments_ThrowArgumentNullException() + { + var collector = new LogCollector(); + var logging = Host.CreateApplicationBuilder().Logging; + + var nullBuilder = () => ComponoLoggingBuilderExtensions.AddComponoCapture(null!, collector); + var nullCollector = () => logging.AddComponoCapture(null!); + + nullBuilder.Should().Throw(); + nullCollector.Should().Throw(); + } + + [Fact] + public void AddComponoCapture_ReturnsTheSameBuilderForChaining() + { + var builder = Host.CreateApplicationBuilder(); + var logging = builder.Logging; + + var returned = logging.AddComponoCapture(new LogCollector()); + + returned.Should().BeSameAs(logging); + } + + [Fact] + public void EmptyCollector_GetLastIsNullAndVerifyNeverPasses() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + + _ = host.Services.GetRequiredService(); + + collector.GetCapturedEntries().Should().BeEmpty(); + collector.GetLastCapturedEntry().Should().BeNull(); + collector.Verify().Never(); + } + + [Fact] + public void ClearCapturedEntries_DiscardsHostCaptures() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Clear.Category"); + logger.LogInformation("one"); + logger.LogInformation("two"); + + collector.ClearCapturedEntries(); + + collector.GetCapturedEntries().Should().BeEmpty(); + collector.GetLastCapturedEntry().Should().BeNull(); + } + + private static IHost CreateHost(LogCollector collector, Action? configure = null) + { + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + configure?.Invoke(builder); + return builder.Build(); + } +} + +public sealed class HostScopeCaptureTests +{ + [Fact] + public async Task NestedScopesAcrossAwait_AreCapturedOutermostFirst() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Scopes.Category"); + + using (logger.BeginScope("Outer")) + { + await Task.Yield(); + using (logger.BeginScope("Inner")) + { + await Task.Yield(); + logger.LogInformation("inside"); + } + } + + var scopes = collector.GetLastCapturedEntry()!.Value.Scopes; + scopes.Should().HaveCount(2); + scopes[0].Should().Be("Outer"); + scopes[1].Should().Be("Inner"); + } + + [Fact] + public void DictionaryScope_IsCapturedAsTheSameInstance() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Scopes.Category"); + var scope = new Dictionary { ["OrderId"] = 42 }; + + using (logger.BeginScope(scope)) + logger.LogInformation("inside"); + + collector.GetLastCapturedEntry()!.Value.Scopes.Should().ContainSingle().Which.Should().BeSameAs(scope); + } + + [Fact] + public async Task SiblingTasks_KeepTheirScopesIsolated() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Scopes.Category"); + using var startGate = new Barrier(2); + + var first = Task.Run(() => + { + startGate.SignalAndWait(TestContext.Current.CancellationToken); + using (logger.BeginScope("TaskA")) + logger.LogInformation("from A"); + }, TestContext.Current.CancellationToken); + + var second = Task.Run(() => + { + startGate.SignalAndWait(TestContext.Current.CancellationToken); + using (logger.BeginScope("TaskB")) + logger.LogInformation("from B"); + }, TestContext.Current.CancellationToken); + + await Task.WhenAll(first, second); + + var entries = collector.GetCapturedEntries(); + entries.Single(entry => entry.Message == "from A").Scopes.Should().ContainSingle().Which.Should().Be("TaskA"); + entries.Single(entry => entry.Message == "from B").Scopes.Should().ContainSingle().Which.Should().Be("TaskB"); + } + + [Fact] + public void ActivityTrackingOptions_AddsActivityScope() + { + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + builder.Services.Configure( + options => options.ActivityTrackingOptions = ActivityTrackingOptions.TraceId | ActivityTrackingOptions.SpanId); + using var host = builder.Build(); + var logger = host.Services.GetRequiredService().CreateLogger("Activity.Category"); + + using var activity = new Activity("compono-test").Start(); + logger.LogInformation("with activity"); + + var scopes = collector.GetLastCapturedEntry()!.Value.Scopes; + scopes.Should().Contain(scope => scope.ToString()!.Contains(activity.TraceId.ToHexString(), StringComparison.Ordinal)); + } + + private static IHost CreateHost(LogCollector collector) + { + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + return builder.Build(); + } +} diff --git a/test/Compono.Logging.Tests/LogCollectorDisposalAndIsolationTests.cs b/test/Compono.Logging.Tests/LogCollectorDisposalAndIsolationTests.cs new file mode 100644 index 00000000..4e2f7feb --- /dev/null +++ b/test/Compono.Logging.Tests/LogCollectorDisposalAndIsolationTests.cs @@ -0,0 +1,281 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Compono.Logging.Tests; + +public sealed class LogCollectorDisposalAndIsolationTests +{ + private static readonly LogLevel[] OrdinaryLevels = + [ + LogLevel.Trace, + LogLevel.Debug, + LogLevel.Information, + LogLevel.Warning, + LogLevel.Error, + LogLevel.Critical, + ]; + + [Fact] + public void DisposingHost_DisposesProvider_ButCollectorStaysReadable() + { + var collector = new LogCollector(); + var host = CreateHost(collector); + var factoryLogger = host.Services.GetRequiredService().CreateLogger("Held.Category"); + var containerLogger = host.Services.GetRequiredService>(); + var provider = host.Services.GetServices().OfType().Single(); + + factoryLogger.LogInformation("before"); + containerLogger.LogInformation("before container"); + + host.Dispose(); + + provider.IsDisposed.Should().BeTrue(); + collector.GetCapturedEntries().Should().HaveCount(2); + collector.GetLastCapturedEntry()!.Value.Message.Should().Be("before container"); + collector.Verify().Exactly(2); + } + + [Fact] + public void HeldLoggersAfterDisposal_ReportDisabledAndSilentlyIgnoreEveryLevel() + { + var collector = new LogCollector(); + var host = CreateHost(collector); + var factoryLogger = host.Services.GetRequiredService().CreateLogger("Held.Category"); + var containerLogger = host.Services.GetRequiredService>(); + factoryLogger.LogInformation("before"); + host.Dispose(); + + foreach (var level in OrdinaryLevels) + { + factoryLogger.IsEnabled(level).Should().BeFalse(); + containerLogger.IsEnabled(level).Should().BeFalse(); + factoryLogger.Log(level, new EventId(1), "after", null, static (state, _) => state); + containerLogger.Log(level, new EventId(1), "after", null, static (state, _) => state); + } + + collector.GetCapturedEntries().Should().ContainSingle(); + collector.GetLastCapturedEntry()!.Value.Message.Should().Be("before"); + } + + [Fact] + public void HeldLoggersAfterDisposal_BeginScopeReturnsUsableDisposableAndDoesNotThrow() + { + var collector = new LogCollector(); + var host = CreateHost(collector); + var logger = host.Services.GetRequiredService>(); + host.Dispose(); + + var act = () => + { + using var scope = logger.BeginScope("after disposal"); + scope.Should().NotBeNull(); + }; + + act.Should().NotThrow(); + } + + [Fact] + public void ProviderCreateLoggerAfterDisposal_ReturnsNonCapturingLogger() + { + var collector = new LogCollector(); + var host = CreateHost(collector); + var provider = host.Services.GetServices().OfType().Single(); + host.Dispose(); + + var logger = provider.CreateLogger("After.Disposal"); + + logger.IsEnabled(LogLevel.Information).Should().BeFalse(); + logger.LogInformation("ignored"); + using var scope = logger.BeginScope("still usable"); + collector.GetCapturedEntries().Should().BeEmpty(); + } + + [Fact] + public void DisposalIsIdempotent_AndNeverClearsOrDetachesTheCollector() + { + var collector = new LogCollector(); + var host = CreateHost(collector); + host.Services.GetRequiredService().CreateLogger("Idempotent").LogInformation("kept"); + var provider = host.Services.GetServices().OfType().Single(); + + host.Dispose(); + host.Dispose(); + provider.Dispose(); + + collector.GetCapturedEntries().Should().ContainSingle().Which.Message.Should().Be("kept"); + + collector.ClearCapturedEntries(); + + collector.GetCapturedEntries().Should().BeEmpty(); + } + + [Fact] + public void DisposingOneHost_StopsOnlyThatHostsCapture_ForASharedCollector() + { + var collector = new LogCollector(); + var firstHost = CreateHost(collector); + var secondHost = CreateHost(collector); + var firstLogger = firstHost.Services.GetRequiredService().CreateLogger("First"); + var secondLogger = secondHost.Services.GetRequiredService().CreateLogger("Second"); + + firstLogger.LogInformation("first before"); + secondLogger.LogInformation("second before"); + + firstHost.Dispose(); + + firstLogger.LogInformation("first after"); + secondLogger.LogInformation("second after"); + + var entries = collector.GetCapturedEntries(); + entries.Should().HaveCount(3); + entries.Should().NotContain(entry => entry.Message == "first after"); + entries.Should().Contain(entry => entry.Message == "second after"); + + secondHost.Dispose(); + } + + [Fact] + public async Task ParallelHostsWithSeparateCollectors_ShareNothing() + { + const int perTask = 200; + var first = new LogCollector(); + var second = new LogCollector(); + using var firstHost = CreateHost(first); + using var secondHost = CreateHost(second); + var firstLogger = firstHost.Services.GetRequiredService().CreateLogger("First.Category"); + var secondLogger = secondHost.Services.GetRequiredService().CreateLogger("Second.Category"); + using var startGate = new Barrier(2); + + var firstWriter = Task.Run(() => + { + startGate.SignalAndWait(TestContext.Current.CancellationToken); + for (var i = 0; i < perTask; i++) + firstLogger.LogInformation("first {Index}", i); + }, TestContext.Current.CancellationToken); + + var secondWriter = Task.Run(() => + { + startGate.SignalAndWait(TestContext.Current.CancellationToken); + for (var i = 0; i < perTask; i++) + secondLogger.LogInformation("second {Index}", i); + }, TestContext.Current.CancellationToken); + + await Task.WhenAll(firstWriter, secondWriter); + + first.GetCapturedEntries().Should().HaveCount(perTask).And.OnlyContain(entry => entry.Category == "First.Category"); + second.GetCapturedEntries().Should().HaveCount(perTask).And.OnlyContain(entry => entry.Category == "Second.Category"); + } + + [Fact] + public async Task ConcurrentWritesAndReads_NeverThrowOrCorrupt() + { + // RESEARCH-0033: both participants have fixed iteration counts; neither termination depends + // on the other, so the captured-entry upper bound stays compile-time constant. + const int taskCount = 4; + const int perTask = 500; + const int readIterations = 50; + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Concurrent.Category"); + using var startGate = new Barrier(taskCount + 1); + + var writers = Enumerable.Range(0, taskCount).Select(writer => Task.Run(() => + { + startGate.SignalAndWait(TestContext.Current.CancellationToken); + for (var i = 0; i < perTask; i++) + logger.LogInformation("writer {Writer} entry {Index}", writer, i); + }, TestContext.Current.CancellationToken)).ToArray(); + + var reader = Task.Run(() => + { + startGate.SignalAndWait(TestContext.Current.CancellationToken); + for (var i = 0; i < readIterations; i++) + { + var entries = collector.GetCapturedEntries(); + foreach (var entry in entries) + _ = entry.Message; + + _ = collector.GetLastCapturedEntry(); + collector.Verify().AtLeast(0); + } + }, TestContext.Current.CancellationToken); + + await Task.WhenAll([.. writers, reader]); + + collector.GetCapturedEntries().Should().HaveCount(taskCount * perTask); + } + + [Fact] + public async Task ConcurrentClearWithWrites_NeverThrowsAndLeavesConsistentSnapshots() + { + const int writeCount = 1_000; + const int clearIterations = 100; + var collector = new LogCollector(); + using var host = CreateHost(collector); + var logger = host.Services.GetRequiredService().CreateLogger("Clear.Category"); + using var startGate = new Barrier(2); + + var writer = Task.Run(() => + { + startGate.SignalAndWait(TestContext.Current.CancellationToken); + for (var i = 0; i < writeCount; i++) + logger.LogInformation("write {Index}", i); + }, TestContext.Current.CancellationToken); + + var clearer = Task.Run(() => + { + startGate.SignalAndWait(TestContext.Current.CancellationToken); + for (var i = 0; i < clearIterations; i++) + { + collector.ClearCapturedEntries(); + collector.GetCapturedEntries().Should().OnlyContain(entry => entry.Category == "Clear.Category"); + } + }, TestContext.Current.CancellationToken); + + await Task.WhenAll(writer, clearer); + + collector.GetCapturedEntries().Should().HaveCountLessThanOrEqualTo(writeCount); + } + + [Fact] + public void ComposedAndHostCapture_AreSeparateDestinations() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var composer = Composer.Create(builder => builder.UseLogging()); + var composed = composer.Create(); + + composed.PlaceOrder(1); + + composed.Logger.GetCapturedEntries().Should().ContainSingle(); + collector.GetCapturedEntries().Should().BeEmpty(); + + var hostLogger = host.Services.GetRequiredService>(); + hostLogger.LogWarning("host only"); + + collector.GetCapturedEntries().Should().ContainSingle(); + composed.Logger.GetCapturedEntries().Should().ContainSingle(); + } + + [Fact] + public void VerifyOnAHostLogger_ThrowsAndPointsAtLogCollector() + { + var collector = new LogCollector(); + using var host = CreateHost(collector); + var hostLogger = host.Services.GetRequiredService>(); + + var act = () => hostLogger.Verify(); + + act.Should().Throw() + .WithMessage("*LogCollector*AddComponoCapture*"); + } + + private static IHost CreateHost(LogCollector collector) + { + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + return builder.Build(); + } +} diff --git a/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs b/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs new file mode 100644 index 00000000..d7cebf4c --- /dev/null +++ b/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs @@ -0,0 +1,65 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Compono.Logging.Tests; + +public sealed class LogCollectorRegistrationTests +{ + [Fact] + public void SameCollectorRegisteredTwice_ProducesOneProviderAndOneCopyOfEachEntry() + { + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + builder.Logging.AddComponoCapture(collector); + using var host = builder.Build(); + + host.Services.GetRequiredService().CreateLogger("Cardinality.Category").LogInformation("once"); + + host.Services.GetServices().OfType().Should().ContainSingle(); + collector.GetCapturedEntries().Should().ContainSingle(); + } + + [Fact] + public void DifferentCollectorsOnOneBuilder_EachReceivesEveryEntry() + { + var first = new LogCollector(); + var second = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(first); + builder.Logging.AddComponoCapture(second); + using var host = builder.Build(); + + host.Services.GetRequiredService().CreateLogger("Cardinality.Category").LogInformation("everyone"); + + host.Services.GetServices().OfType().Should().HaveCount(2); + first.GetCapturedEntries().Should().ContainSingle().Which.Message.Should().Be("everyone"); + second.GetCapturedEntries().Should().ContainSingle().Which.Message.Should().Be("everyone"); + } + + [Fact] + public void SameCollectorAcrossTwoHosts_ReceivesEntriesFromBoth() + { + var collector = new LogCollector(); + using var firstHost = CreateHost(collector); + using var secondHost = CreateHost(collector); + + firstHost.Services.GetRequiredService().CreateLogger("First").LogInformation("from first"); + secondHost.Services.GetRequiredService().CreateLogger("Second").LogInformation("from second"); + + collector.GetCapturedEntries().Should().HaveCount(2); + collector.GetCapturedEntries().Should().Contain(entry => entry.Message == "from first"); + collector.GetCapturedEntries().Should().Contain(entry => entry.Message == "from second"); + } + + private static IHost CreateHost(LogCollector collector) + { + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + return builder.Build(); + } +} diff --git a/test/Compono.Logging.Tests/LogVerificationBuilderExtendedFilterTests.cs b/test/Compono.Logging.Tests/LogVerificationBuilderExtendedFilterTests.cs new file mode 100644 index 00000000..3f1c75b5 --- /dev/null +++ b/test/Compono.Logging.Tests/LogVerificationBuilderExtendedFilterTests.cs @@ -0,0 +1,138 @@ +using Microsoft.Extensions.Logging; + +namespace Compono.Logging.Tests; + +public sealed class LogVerificationBuilderExtendedFilterTests +{ + private static readonly DateTimeOffset Timestamp = new(2026, 11, 11, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public void AtLevelOrAbove_Trace_MatchesEveryCapturedLevel() + { + var logger = new CapturingLogger(); + + logger.LogTrace("trace"); + logger.LogDebug("debug"); + logger.LogInformation("information"); + logger.LogWarning("warning"); + logger.LogError("error"); + logger.LogCritical("critical"); + + logger.Verify().AtLevelOrAbove(LogLevel.Trace).Exactly(6); + } + + [Fact] + public void AtLevelOrAbove_Warning_ExcludesLessSevereLevels() + { + var logger = new CapturingLogger(); + + logger.LogInformation("information"); + logger.LogWarning("warning"); + logger.LogError("error"); + logger.LogCritical("critical"); + + logger.Verify().AtLevelOrAbove(LogLevel.Warning).Exactly(3); + } + + [Fact] + public void AtLevelOrAbove_Error_MatchesErrorAndCriticalOnly() + { + var logger = new CapturingLogger(); + + logger.LogWarning("warning"); + logger.LogError("error"); + logger.LogCritical("critical"); + + logger.Verify().AtLevelOrAbove(LogLevel.Error).Exactly(2); + logger.Verify().AtLevelOrAbove(LogLevel.Critical).Once(); + } + + [Fact] + public void AtLevelOrAbove_None_MatchesNothing_EvenIfAnEntryIsPresent() + { + var collector = new LogCollector(); + collector.Add(CreateEntry("Category.A", LogLevel.Critical)); + + collector.Verify().AtLevelOrAbove(LogLevel.None).Never(); + } + + [Fact] + public void AtLevelOrAbove_CombinesWithOtherFilters() + { + var collector = new LogCollector(); + collector.Add(CreateEntry("Category.A", LogLevel.Error, "first")); + collector.Add(CreateEntry("Category.B", LogLevel.Error, "second")); + collector.Add(CreateEntry("Category.A", LogLevel.Warning, "retrying order")); + + collector.Verify() + .AtLevelOrAbove(LogLevel.Error) + .InCategory("Category.A") + .WithMessageContaining("first") + .Once(); + } + + [Fact] + public void AtLevelOrAbove_FailureMessageNamesTheLevelAndAbove() + { + var logger = new CapturingLogger(); + logger.LogError("boom"); + + var act = () => logger.Verify().AtLevelOrAbove(LogLevel.Error).Never(); + + act.Should().Throw() + .WithMessage("Expected exactly 0 call(s) to a log entry matching level Error or above, but received 1."); + } + + [Fact] + public void InCategory_MatchesExactCategory() + { + var collector = new LogCollector(); + collector.Add(CreateEntry("Category.A", LogLevel.Information)); + collector.Add(CreateEntry("Category.B", LogLevel.Information)); + + collector.Verify().InCategory("Category.A").Once(); + } + + [Fact] + public void InCategory_IsCaseSensitive() + { + var collector = new LogCollector(); + collector.Add(CreateEntry("Category.A", LogLevel.Information)); + + collector.Verify().InCategory("category.a").Never(); + } + + [Fact] + public void InCategory_DoesNotMatchPrefix() + { + var collector = new LogCollector(); + collector.Add(CreateEntry("Category.A.Nested", LogLevel.Information)); + + collector.Verify().InCategory("Category.A").Never(); + } + + [Fact] + public void InCategory_Null_ThrowsArgumentNullException() + { + var collector = new LogCollector(); + + var act = () => collector.Verify().InCategory(null!); + + act.Should().Throw(); + } + + [Fact] + public void InCategory_FailureMessageNamesTheCategory() + { + var collector = new LogCollector(); + collector.Add(CreateEntry("Category.B", LogLevel.Information)); + + var act = () => collector.Verify().InCategory("Category.A").Once(); + + act.Should().Throw() + .WithMessage("Expected exactly 1 call(s) to a log entry matching category \"Category.A\", but received 0."); + } + + private static CapturedLogEntry CreateEntry(string category, LogLevel level, string message = "message") => + new(category, level, default, null, message, null, null, null, [], Timestamp); +} diff --git a/test/Compono.Logging.Tests/TestCategoryProbe.cs b/test/Compono.Logging.Tests/TestCategoryProbe.cs new file mode 100644 index 00000000..5c14fe70 --- /dev/null +++ b/test/Compono.Logging.Tests/TestCategoryProbe.cs @@ -0,0 +1,35 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Compono.Logging.Tests; + +internal static class TestCategoryProbe +{ + public static string For() + { + // Ask the real LoggerFactory, so parity is proven against the BCL's own naming rules rather + // than a hard-coded string or a re-implementation of those rules. + var probe = new ProbeProvider(); + using var factory = LoggerFactory.Create(builder => builder.AddProvider(probe)); + + factory.CreateLogger().LogInformation("probe"); + + probe.LastCategory.Should().NotBeNull(); + return probe.LastCategory!; + } + + private sealed class ProbeProvider : ILoggerProvider + { + public string? LastCategory { get; private set; } + + public ILogger CreateLogger(string categoryName) + { + LastCategory = categoryName; + return NullLogger.Instance; + } + + public void Dispose() + { + } + } +} From d70c6db4e766bb9aaec122b6a6beddd528ad96ce Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Wed, 11 Nov 2026 07:29:46 -0500 Subject: [PATCH 2/6] docs(plan): record #164 validation and PR #177 (PLAN-0072) --- ...gging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md b/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md index f6b7b41f..675ca8bc 100644 --- a/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md +++ b/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md @@ -517,7 +517,7 @@ and B4, B5, and B6 done. - [x] B7.1 Full validation green - [x] B7.2 Acceptance-criteria cross-check table in Notes -- [ ] B7.3 Plan closeout, PR 2 opened with product-owner approval +- [x] B7.3 Plan closeout, PR 2 opened with product-owner approval (PR #177) ### B0: product-owner acceptance (precedes everything) @@ -710,7 +710,8 @@ python3 -c "import json;json.load(open('skills/compono/evals/evals.json'))" index + documentation architecture); troubleshooting entries for host `ILogger` `Verify()` and missing Debug entries; `skills/compono/references/logging.md` + `SKILL.md`; two new evals. - - Release-note line for the v1.4.0 draft author (not edited here): + - PR 2: #177 (`feat/164-host-wide-log-capture`). Release-note line for the + v1.4.0 draft author (not edited here): "`Compono.Logging`: `CapturedLogEntry` equality now includes the new `Category` property. This is a behavioral change to value equality, not a source or binary breaking change." From 61c3bfd34c0c76ef906b72e3edd8c622021c3e0e Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Wed, 11 Nov 2026 07:35:19 -0500 Subject: [PATCH 3/6] docs(logging): fix host-wide capture anchor for strict mkdocs --- docs/how-to/assert-nothing-logged-at-error-across-a-host.md | 4 ++-- docs/packages/compono-logging.md | 2 +- docs/troubleshooting/common-errors.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/how-to/assert-nothing-logged-at-error-across-a-host.md b/docs/how-to/assert-nothing-logged-at-error-across-a-host.md index 2ffcc8f3..99e317bb 100644 --- a/docs/how-to/assert-nothing-logged-at-error-across-a-host.md +++ b/docs/how-to/assert-nothing-logged-at-error-across-a-host.md @@ -4,7 +4,7 @@ Register a `LogCollector` on the host's logging pipeline, run the host, then verify the collector. The collector is the test-owned capture destination: it sees every category the host logs to, regardless of which `ILogger` produced the entry. See -[`Compono.Logging`'s Package Guide](../packages/compono-logging.md#host-wide-capture-logcollector--addcomponocapture) +[`Compono.Logging`'s Package Guide](../packages/compono-logging.md#host-wide-capture-with-logcollector-and-addcomponocapture) for the full host-wide semantics. ## Basic case @@ -102,7 +102,7 @@ after the request or startup path under test. ## See also -- [Host-wide capture](../packages/compono-logging.md#host-wide-capture-logcollector--addcomponocapture) +- [Host-wide capture](../packages/compono-logging.md#host-wide-capture-with-logcollector-and-addcomponocapture) — Category, filters, ownership, and cardinality rules. - [Share a Value Across a Test](share-a-value-across-a-test.md) — when a service under test needs a specific `ILogger` rather than host-wide diff --git a/docs/packages/compono-logging.md b/docs/packages/compono-logging.md index 18a2a862..245ae443 100644 --- a/docs/packages/compono-logging.md +++ b/docs/packages/compono-logging.md @@ -104,7 +104,7 @@ Console.WriteLine(failure.Properties?.First().Key); // "OrderId", e.g. A provider-composed logger and a directly-constructed one behave identically — one implementation, not two. -## Host-wide capture: `LogCollector` + `AddComponoCapture` +## Host-wide capture with LogCollector and AddComponoCapture Composed loggers only see what Compono composed. A real Generic Host (or `WebApplicationFactory`, or anything else with an diff --git a/docs/troubleshooting/common-errors.md b/docs/troubleshooting/common-errors.md index 5da164c7..02ce153c 100644 --- a/docs/troubleshooting/common-errors.md +++ b/docs/troubleshooting/common-errors.md @@ -308,7 +308,7 @@ Host-wide capture is a **separate destination** from per-logger capture in v1: register a `LogCollector` on the host's logging pipeline with `AddComponoCapture()`, then call `Verify()`/`GetCapturedEntries()` on the collector instead of on the host logger. See -[Host-wide capture](../packages/compono-logging.md#host-wide-capture-logcollector--addcomponocapture) +[Host-wide capture](../packages/compono-logging.md#host-wide-capture-with-logcollector-and-addcomponocapture) and [How Do I Assert Nothing Logged at Error or Above Across a Generic Host?](../how-to/assert-nothing-logged-at-error-across-a-host.md). From 6cfc85284df0c90f32526ced23de2d217b27b5ca Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Wed, 11 Nov 2026 07:48:03 -0500 Subject: [PATCH 4/6] test(logging): cover fallback scopes and multi-category concurrency --- docs/packages/compono-logging.md | 4 +- ...-log-capture-and-dotnet-11-ga-impl-plan.md | 26 +++++++--- .../ComponoLogCollectorProvider.cs | 2 +- src/Compono.Logging/LoggerCategoryName.cs | 4 ++ test/Compono.Logging.AotSmokeTest/Program.cs | 1 - test/Compono.Logging.Tests/CategoryTests.cs | 22 +++++++++ .../Compono.Logging.Tests.csproj | 3 +- .../ComponoLogCollectorProviderTests.cs | 37 ++++++++++++++ .../GlobalCategoryType.cs | 5 +- .../HostLogCaptureTests.cs | 2 +- .../LogCollectorDisposalAndIsolationTests.cs | 49 +++++++++++++++++++ 11 files changed, 141 insertions(+), 14 deletions(-) create mode 100644 test/Compono.Logging.Tests/ComponoLogCollectorProviderTests.cs diff --git a/docs/packages/compono-logging.md b/docs/packages/compono-logging.md index 245ae443..6712cbe7 100644 --- a/docs/packages/compono-logging.md +++ b/docs/packages/compono-logging.md @@ -11,7 +11,7 @@ registered with `AddComponoCapture()` captures a real Generic Host's so a test can assert something like "nothing at `Error` or above was logged anywhere in the host." See [ADR-0055](../adr/0055-compono-logging-testing-support-package.md) (and -its three amendments) for the full decision record and +its amendments) for the full decision record and [RESEARCH-0013](../research/0013-compono-logging-testing-design-research.md) for the design investigation this package's shape came from. @@ -458,4 +458,4 @@ the rationale behind each: note above if a composed type depends on both an `ILogger` and another interface. - [ADR-0055](../adr/0055-compono-logging-testing-support-package.md) — - the full decision record, including its three amendments. + the full decision record, including its amendments. diff --git a/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md b/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md index 675ca8bc..4b505fbf 100644 --- a/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md +++ b/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md @@ -675,21 +675,23 @@ python3 -c "import json;json.load(open('skills/compono/evals/evals.json'))" The attribute is compiled under `#if NET10_0_OR_GREATER`, the shipped dependency graph is unchanged, and the alias config rule is tested only on net10/net11. Recorded as ADR-0071 Amendment 1 (2026-11-11). - - Tests: `test/Compono.Logging.Tests` 490 passed / 0 failed across + - Tests: `test/Compono.Logging.Tests` 514 passed / 0 failed across net8.0/net9.0/net10.0/net11.0. New coverage: MEL category parity - against a real `LoggerFactory` probe (including nested, generic, - global-namespace, built-in and array categories), equality regression - for `Category`, both new filters and their failure text, real Generic + against a real `LoggerFactory` probe (including nested, closed and + multi-argument generics, global-namespace, built-in and array + categories), equality regression for `Category`, both new filters and + their failure text, the provider's fallback scope source, real Generic Host capture (arbitrary/container categories, host lifetime, every entry field, `[LoggerMessage]`, scopes across `await`, sibling-task isolation, activity scopes), host filtering (default Information minimum, `SetMinimumLevel`, `AddFilter`, net10+ alias), cardinality, disposal (post-dispose loggers disabled, entries remain readable, `Clear` still works, double dispose safe, two-host - independence), isolation, and bounded concurrency. + independence), isolation, and bounded concurrency (including multi-category + writes racing reads and clears). - Validation (B7): `dotnet build Compono.slnx -c Release` 0 warnings / - 0 errors; `dotnet test Compono.slnx -c Release --no-build` 7033 - total, 0 failed, 6532 succeeded, 501 skipped. + 0 errors; `dotnet test Compono.slnx -c Release --no-build` 7057 + total, 0 failed, 6556 succeeded, 501 skipped. - AOT (V3 logging leg): pack-and-publish `net10.0`/`osx-arm64` `PublishAot=true` binary passed, host-wide capture and category parity assertions included, and the publish emitted zero IL2xxx/ @@ -726,3 +728,13 @@ python3 -c "import json;json.load(open('skills/compono/evals/evals.json'))" | 5 | Host/composed relationship documented | ADR-0071; package doc "Host vs. composed"; logging skill | | 6 | No new package dependency | `Compono.Logging.csproj` unchanged; packed dependency groups identical | | 7 | Native AOT/trimming retained | `IsAotCompatible` unchanged; AOT smoke publish zero IL warnings | +- 2026-11-11 (independent review follow-up, PR #177): addressed review + findings by fixing the test csproj comment placement and stale amendment + count, marking the provider scope field `volatile`, documenting the + deliberate `!` uses in `LoggerCategoryName`, renaming the alias test to + describe what it proves, and adding tests for the provider fallback scope + source, multi-argument generic and nested global-namespace categories, + `InCategory("")` on a bare logger, and multi-category writes racing reads + and clears. Re-ran focused logging tests (514 passed/0 failed per TFM), + full build 0/0, full suite 7057 total/0 failed, and the AOT logging leg + (PASS, zero IL warnings). diff --git a/src/Compono.Logging/ComponoLogCollectorProvider.cs b/src/Compono.Logging/ComponoLogCollectorProvider.cs index 08dcd1f8..336fc79d 100644 --- a/src/Compono.Logging/ComponoLogCollectorProvider.cs +++ b/src/Compono.Logging/ComponoLogCollectorProvider.cs @@ -22,7 +22,7 @@ internal sealed class ComponoLogCollectorProvider : ILoggerProvider, ISupportExt { private readonly LogCollector _collector; private readonly LoggerExternalScopeProvider _fallbackScopeProvider = new(); - private IExternalScopeProvider? _scopeProvider; + private volatile IExternalScopeProvider? _scopeProvider; private volatile bool _disposed; public ComponoLogCollectorProvider(LogCollector collector) diff --git a/src/Compono.Logging/LoggerCategoryName.cs b/src/Compono.Logging/LoggerCategoryName.cs index 6b4ab8a2..849b1c4f 100644 --- a/src/Compono.Logging/LoggerCategoryName.cs +++ b/src/Compono.Logging/LoggerCategoryName.cs @@ -56,6 +56,7 @@ private static void AppendType(StringBuilder builder, Type type) } else { + // FullName is present for every constructed runtime type; '+' separates nested types. builder.Append(type.FullName!.Replace('+', '.')); } } @@ -64,6 +65,7 @@ private static void AppendArrayType(StringBuilder builder, Type type) { var elementType = type; while (elementType.IsArray) + // IsArray guarantees an element type. elementType = elementType.GetElementType()!; AppendType(builder, elementType); @@ -73,6 +75,7 @@ private static void AppendArrayType(StringBuilder builder, Type type) builder.Append('['); builder.Append(',', type.GetArrayRank() - 1); builder.Append(']'); + // IsArray is re-checked by the loop condition. type = type.GetElementType()!; } } @@ -81,6 +84,7 @@ private static void AppendGenericType(StringBuilder builder, Type type) { if (type.IsNested) { + // IsNested guarantees a declaring type. AppendType(builder, type.DeclaringType!); builder.Append('.'); } diff --git a/test/Compono.Logging.AotSmokeTest/Program.cs b/test/Compono.Logging.AotSmokeTest/Program.cs index e53de28e..0b6e5f4e 100644 --- a/test/Compono.Logging.AotSmokeTest/Program.cs +++ b/test/Compono.Logging.AotSmokeTest/Program.cs @@ -82,7 +82,6 @@ private static void VerifyHostWideCapture() if (collector.GetCapturedEntries().Count != 1) throw new InvalidOperationException($"Expected exactly 1 host-captured entry, got {collector.GetCapturedEntries().Count}."); - var entry = collector.GetLastCapturedEntry()!.Value; if (entry.Category != "Host.Smoke") throw new InvalidOperationException($"Expected Host.Smoke category, got '{entry.Category}'."); diff --git a/test/Compono.Logging.Tests/CategoryTests.cs b/test/Compono.Logging.Tests/CategoryTests.cs index 620cd4c5..bd190ae8 100644 --- a/test/Compono.Logging.Tests/CategoryTests.cs +++ b/test/Compono.Logging.Tests/CategoryTests.cs @@ -46,6 +46,19 @@ public void GenericLogger_CategoryMatchesLoggerFactory_ForGlobalNamespaceType() AssertCategoryMatchesFactory(); } + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForNestedTypeInGlobalNamespaceType() + { + AssertCategoryMatchesFactory(); + } + + [Fact] + public void GenericLogger_CategoryMatchesLoggerFactory_ForMultiArgumentGenericType() + { + AssertCategoryMatchesFactory>(); + AssertCategoryMatchesFactory<(int, string)>(); + } + [Fact] public void GenericLogger_CategoryMatchesLoggerFactory_ForBuiltInTypes() { @@ -95,6 +108,15 @@ public void ComposedBareILogger_CategoryIsEmpty() logger.GetCapturedEntries()[0].Category.Should().BeEmpty(); } + [Fact] + public void BareCapturingLogger_InCategoryEmptyString_MatchesItsEntries() + { + var logger = new CapturingLogger(); + logger.LogInformation("captured"); + + logger.Verify().InCategory(string.Empty).Once(); + } + [Fact] public void Equality_IncludesCategory_IntentionalBehavioralChangeFromAdr0071() { diff --git a/test/Compono.Logging.Tests/Compono.Logging.Tests.csproj b/test/Compono.Logging.Tests/Compono.Logging.Tests.csproj index c660c7a0..980273f1 100644 --- a/test/Compono.Logging.Tests/Compono.Logging.Tests.csproj +++ b/test/Compono.Logging.Tests/Compono.Logging.Tests.csproj @@ -46,7 +46,8 @@ capture tests exercise a real IServiceProvider/host lifecycle. Compono.Logging itself never references either (ADR-0071's Abstractions-only dependency graph is unaffected). --> - diff --git a/test/Compono.Logging.Tests/ComponoLogCollectorProviderTests.cs b/test/Compono.Logging.Tests/ComponoLogCollectorProviderTests.cs new file mode 100644 index 00000000..adb091bd --- /dev/null +++ b/test/Compono.Logging.Tests/ComponoLogCollectorProviderTests.cs @@ -0,0 +1,37 @@ +using Microsoft.Extensions.Logging; + +namespace Compono.Logging.Tests; + +public sealed class ComponoLogCollectorProviderTests +{ + [Fact] + public void LoggerWithoutHostScopeProvider_FallsBackToItsOwnScopeProvider() + { + var collector = new LogCollector(); + using var provider = new ComponoLogCollectorProvider(collector); + var logger = provider.CreateLogger("Fallback.Category"); + + using (logger.BeginScope("outer")) + using (logger.BeginScope("inner")) + logger.LogInformation("captured"); + + var entry = collector.GetCapturedEntries().Should().ContainSingle().Subject; + entry.Scopes.Should().Equal("outer", "inner"); + } + + [Fact] + public void SetScopeProvider_ReplacesTheFallbackScopeSource() + { + var collector = new LogCollector(); + using var provider = new ComponoLogCollectorProvider(collector); + var external = new LoggerExternalScopeProvider(); + provider.SetScopeProvider(external); + var logger = provider.CreateLogger("External.Category"); + + using (logger.BeginScope("external scope")) + logger.LogInformation("captured"); + + var entry = collector.GetCapturedEntries().Should().ContainSingle().Subject; + entry.Scopes.Should().Equal("external scope"); + } +} diff --git a/test/Compono.Logging.Tests/GlobalCategoryType.cs b/test/Compono.Logging.Tests/GlobalCategoryType.cs index bdaab727..4e26f104 100644 --- a/test/Compono.Logging.Tests/GlobalCategoryType.cs +++ b/test/Compono.Logging.Tests/GlobalCategoryType.cs @@ -1,3 +1,6 @@ // Intentionally declared outside any namespace: proves category naming for a global-namespace // type matches LoggerFactory.CreateLogger() exactly. -public sealed class GlobalCategoryType; +public sealed class GlobalCategoryType +{ + public sealed class NestedCategoryType; +} diff --git a/test/Compono.Logging.Tests/HostLogCaptureTests.cs b/test/Compono.Logging.Tests/HostLogCaptureTests.cs index 2e743fa8..d8c4dd24 100644 --- a/test/Compono.Logging.Tests/HostLogCaptureTests.cs +++ b/test/Compono.Logging.Tests/HostLogCaptureTests.cs @@ -206,7 +206,7 @@ public void HostCategoryFilter_ExcludesFilteredEntries() #if NET10_0_OR_GREATER [Fact] - public void ProviderAliasConfiguration_TargetsOnlyTheComponoProvider() + public void ProviderAliasConfiguration_AppliesProviderSpecificRuleToComponoProvider() { // ADR-0071 Amendment 1: [ProviderAlias("Compono")] lives in Logging.Abstractions only on // net10.0+, so this provider-specific configuration rule is a net10/net11 capability; net8 diff --git a/test/Compono.Logging.Tests/LogCollectorDisposalAndIsolationTests.cs b/test/Compono.Logging.Tests/LogCollectorDisposalAndIsolationTests.cs index 4e2f7feb..a8c79b81 100644 --- a/test/Compono.Logging.Tests/LogCollectorDisposalAndIsolationTests.cs +++ b/test/Compono.Logging.Tests/LogCollectorDisposalAndIsolationTests.cs @@ -167,6 +167,55 @@ public async Task ParallelHostsWithSeparateCollectors_ShareNothing() second.GetCapturedEntries().Should().HaveCount(perTask).And.OnlyContain(entry => entry.Category == "Second.Category"); } + [Fact] + public async Task ConcurrentMultiCategoryWritesWithReadsAndClears_NeverThrowOrCorrupt() + { + // RESEARCH-0033: every participant has a fixed iteration count and never waits for another + // participant to stop, so the test cannot hang in CI. + const int categoryCount = 4; + const int perCategory = 300; + const int readIterations = 30; + const int clearIterations = 30; + string[] categories = ["Multi.Category.0", "Multi.Category.1", "Multi.Category.2", "Multi.Category.3"]; + var collector = new LogCollector(); + using var host = CreateHost(collector); + var factory = host.Services.GetRequiredService(); + using var startGate = new Barrier(categoryCount + 2); + + var writers = categories.Select(category => Task.Run(() => + { + var logger = factory.CreateLogger(category); + startGate.SignalAndWait(TestContext.Current.CancellationToken); + for (var i = 0; i < perCategory; i++) + logger.LogInformation("write {Index}", i); + }, TestContext.Current.CancellationToken)).ToArray(); + + var reader = Task.Run(() => + { + startGate.SignalAndWait(TestContext.Current.CancellationToken); + for (var i = 0; i < readIterations; i++) + { + _ = collector.GetCapturedEntries(); + _ = collector.GetLastCapturedEntry(); + collector.Verify().AtLeast(0); + } + }, TestContext.Current.CancellationToken); + + var clearer = Task.Run(() => + { + startGate.SignalAndWait(TestContext.Current.CancellationToken); + for (var i = 0; i < clearIterations; i++) + collector.ClearCapturedEntries(); + }, TestContext.Current.CancellationToken); + + await Task.WhenAll([.. writers, reader, clearer]); + + collector.GetCapturedEntries() + .Should() + .HaveCountLessThanOrEqualTo(categoryCount * perCategory) + .And.OnlyContain(entry => categories.Contains(entry.Category)); + } + [Fact] public async Task ConcurrentWritesAndReads_NeverThrowOrCorrupt() { From 388e35e1ffa8b74b7a3ff281df5eaa0cbbd89dbd Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Wed, 11 Nov 2026 09:01:03 -0500 Subject: [PATCH 5/6] fix(logging): honor capture re-registration and enable Compono alias on every TFM Address the independent review of PR #177 (issue #164): - AddComponoCapture -> ClearProviders -> AddComponoCapture(same collector) silently stopped capturing. Duplicate detection no longer relies on a separate marker descriptor that ClearProviders() leaves behind; it now inspects the live ILoggerProvider descriptor whose factory target is the registration. Adds ClearProviders/re-registration regression tests. - The Compono provider alias now works on net8.0/net9.0 too, not just net10.0+: an internal same-full-name ProviderAliasAttribute copy is compiled on the older TFMs (MEL resolves the alias by full type name), with CS0436 promoted to an error. No new package dependencies. Recorded as ADR-0071 Amendment 2. - Fix host-wide capture docs: InCategory is exact full-type-name matching (not AddFilter-style prefix), Never() does not list matching entries, a shared WebApplicationFactory retains entries between tests, and a replaced ILoggerFactory can bypass registered providers. Validation: full build 0/0; full suite 7087 total/0 failed/6586 succeeded/ 501 skipped; ApiCompat and packed-nupkg inspection clean (additions only, dependency groups unchanged); multi-TFM pack-and-consume of Compono.Logging verifies the alias + filtering on net8.0/net9.0/net10.0/net11.0; net8.0 and net9.0 AOT publishes emit zero IL warnings and honor the alias. --- ...1-compono-logging-host-wide-log-capture.md | 56 +++++++++++++ ...t-nothing-logged-at-error-across-a-host.md | 69 +++++++++++++-- docs/packages/compono-logging.md | 71 ++++++++++++---- ...-log-capture-and-dotnet-11-ga-impl-plan.md | 61 ++++++++++++++ docs/troubleshooting/common-errors.md | 31 +++++-- docs/troubleshooting/index.md | 5 +- skills/compono/evals/evals.json | 27 ++++++ skills/compono/references/logging.md | 41 +++++++-- src/Compono.Logging/Compono.Logging.csproj | 6 ++ .../ComponoCaptureRegistration.cs | 21 +++-- .../ComponoLogCollectorProvider.cs | 12 ++- .../ComponoLoggingBuilderExtensions.cs | 12 ++- src/Compono.Logging/ProviderAliasAttribute.cs | 33 ++++++++ test/Compono.Logging.AotSmokeTest/Program.cs | 23 +++++ .../HostLogCaptureTests.cs | 83 +++++++++++++++++-- .../LogCollectorRegistrationTests.cs | 77 +++++++++++++++++ 16 files changed, 570 insertions(+), 58 deletions(-) create mode 100644 src/Compono.Logging/ProviderAliasAttribute.cs diff --git a/docs/adr/0071-compono-logging-host-wide-log-capture.md b/docs/adr/0071-compono-logging-host-wide-log-capture.md index 2b99663a..0f114d97 100644 --- a/docs/adr/0071-compono-logging-host-wide-log-capture.md +++ b/docs/adr/0071-compono-logging-host-wide-log-capture.md @@ -535,6 +535,62 @@ unchanged in intent but now explicitly version-scoped: No public API or dependency changes. +### Amendment 2 (2026-11-11) — the `Compono` alias works on every target framework + +Independent review of PR #177 found that Amendment 1's premise was +imprecise and its conclusion unnecessary. This amendment corrects it; +Amendment 1's text stays as recorded. + +**Corrected facts** (verified against the restored packages and by +experiment): + +- Availability tracks the **Abstractions package version**, not the + target framework. `ProviderAliasAttribute` is absent from every lib + asset of `Microsoft.Extensions.Logging.Abstractions` 8.0.2 and 9.0.23, + and present in every lib asset (including `lib/net8.0`) of 10.0.15 and + 11.0.0. Amendment 1's `NET10_0_OR_GREATER` split only lined up with + that because this package pins Abstractions to the 8.x/9.x line on + net8.0/net9.0 (`Directory.Packages.props`). +- `Microsoft.Extensions.Logging` resolves a provider's alias **by the + attribute's full type name** (`CustomAttributeData`, comparing + `"Microsoft.Extensions.Logging.ProviderAliasAttribute"`), not by type + identity. A locally defined attribute with that exact full name is + honored; the same simple name in another namespace is not. +- Consequence of Amendment 1 as shipped on net8.0/net9.0: + `Logging:Compono:*` rules were silently ignored, while + `Logging:Compono.Logging.ComponoLogCollectorProvider:*` (the internal + type's full name) did work — an accidental configuration surface. + +**Decision:** keep `[ProviderAlias("Compono")]` unconditional. On +net8.0/net9.0 (`#if !NET10_0_OR_GREATER`) the package compiles an +**internal** `Microsoft.Extensions.Logging.ProviderAliasAttribute` with the +framework attribute's exact full name and constructor shape; on +net10.0/net11.0 the real attribute from Abstractions is used and the copy +compiles to nothing. + +**Verified before adopting it:** + +- Recognition: `Logging:Compono:LogLevel:*` (default and category-prefix + rules) applies to the Compono provider and not to other providers, under + a real Generic Host, in `Compono.Logging.Tests` on all four TFMs. +- No new dependencies: the project file and packed dependency groups are + unchanged. +- No type-identity collision: the copy is internal, so consumers never see + it. A net8.0/net9.0 consumer that references both Compono.Logging and + `Microsoft.Extensions.Logging` and applies the public + `[ProviderAlias(...)]` to its own provider compiles with warnings as + errors and binds to the public attribute. If an Abstractions 10.x+ + reference ever reached net8.0/net9.0, the compiler would flag the + duplicate (CS0436), which `Compono.Logging.csproj` promotes to an error, + instead of changing behavior silently. +- Native AOT: that consumer, published with `PublishAot=true` for net8.0 + and net9.0, produced no IL2xxx/IL3xxx warnings and honored the alias at + runtime. net10.0 keeps its existing `Compono.Logging.AotSmokeTest` + coverage. + +Public API, dependency graph, and every other decision in this ADR are +unchanged. Documentation no longer carries a net8/net9 alias caveat. + ## Links - Issue [#164](https://github.com/LayeredCraft/compono/issues/164); parent diff --git a/docs/how-to/assert-nothing-logged-at-error-across-a-host.md b/docs/how-to/assert-nothing-logged-at-error-across-a-host.md index 99e317bb..f04329cf 100644 --- a/docs/how-to/assert-nothing-logged-at-error-across-a-host.md +++ b/docs/how-to/assert-nothing-logged-at-error-across-a-host.md @@ -32,15 +32,19 @@ public async Task Startup_LogsNothingAtErrorOrAbove() } ``` -`AtLevelOrAbove(LogLevel.Error)` matches `Error`, `Critical`, and anything -else at or above that severity; `LogLevel.None` never matches. `Never()` -fails the test with a message naming the filter and the matching entries, -so a regression reads as: +`AtLevelOrAbove(LogLevel.Error)` matches `Error` and `Critical`; +`LogLevel.None` never matches. `Never()` fails the test with a message +naming the filter and how many entries matched: ```text Expected exactly 0 call(s) to a log entry matching level Error or above, but received 1. ``` +The message doesn't list the offending entries. To see them, read the +collector — for example +`logs.GetCapturedEntries().Where(entry => entry.LogLevel >= LogLevel.Error)` +— in the failing test or a debugger. + ## Narrow it to one category Add `InCategory` when only one subsystem should be checked. The match is @@ -49,13 +53,26 @@ an exact, ordinal, case-sensitive comparison of the entry's `Category`: ```csharp logs.Verify() .AtLevelOrAbove(LogLevel.Error) - .InCategory("Payments.Gateway") + .InCategory("MyApp.Payments.PaymentGateway") .Never(); ``` For a host entry, `Category` is exactly the string the logging pipeline -passed to `ILoggerProvider.CreateLogger` — normally the full name of the -`ILogger` category type. +passed to `ILoggerProvider.CreateLogger` — for an `ILogger`, +the type's full name (`MyApp.Payments.PaymentGateway`), not its namespace +or a short name. + +`InCategory` never matches by prefix, unlike the host's own `AddFilter` +and `Logging:LogLevel:*` rules. A category string that matches nothing +makes `Never()` pass without checking anything. To cover a whole +namespace, match the prefix explicitly: + +```csharp +logs.Verify() + .AtLevelOrAbove(LogLevel.Error) + .Matching(entry => entry.Category.StartsWith("MyApp.Payments.", StringComparison.Ordinal)) + .Never(); +``` ## What the host may not capture @@ -68,7 +85,9 @@ the collector unless the host is configured to allow them: ``` If the host filters a category out with `AddFilter`, that category is -absent from the collector too. This is intentional: the collector reports +absent from the collector too. To filter only what the collector sees, use +the provider's `Compono` alias in configuration, for example +`Logging:Compono:LogLevel:Default`. This is intentional: the collector reports what the host actually logged, not what any logger attempted to log. ## Keep the collector for the whole test @@ -100,6 +119,40 @@ public sealed class ApiFactory : WebApplicationFactory Then assert `factory.Logs.Verify().AtLevelOrAbove(LogLevel.Error).Never()` after the request or startup path under test. +A factory shared across tests (an xUnit class or collection fixture) +shares one collector, and the collector keeps every entry with no size +limit. An error logged by one test would then fail another test's +`Never()`. Clear it at the start of each test: + +```csharp +public sealed class CheckoutTests(ApiFactory factory) : IClassFixture +{ + [Fact] + public async Task Checkout_LogsNothingAtErrorOrAbove() + { + factory.Logs.ClearCapturedEntries(); + + var client = factory.CreateClient(); + await client.PostAsync("/checkout", null, TestContext.Current.CancellationToken); + + factory.Logs.Verify().AtLevelOrAbove(LogLevel.Error).Never(); + } +} +``` + +## When the collector stays empty + +If the application replaces the host's `ILoggerFactory` with one that +ignores registered providers — for example Serilog's `UseSerilog()` +without `writeToProviders: true` — or calls `ClearProviders()` *after* the +test registered the collector, nothing reaches the collector and `Never()` +passes without checking anything. Guard against that by also asserting +something you know the host logs: + +```csharp +logs.Verify().InCategory("Microsoft.Hosting.Lifetime").AtLeast(1); +``` + ## See also - [Host-wide capture](../packages/compono-logging.md#host-wide-capture-with-logcollector-and-addcomponocapture) diff --git a/docs/packages/compono-logging.md b/docs/packages/compono-logging.md index 6712cbe7..a6b3d20a 100644 --- a/docs/packages/compono-logging.md +++ b/docs/packages/compono-logging.md @@ -126,7 +126,13 @@ using var host = builder.Build(); // ... start the host, call the code under test ... -logs.Verify().AtLevelOrAbove(LogLevel.Error).InCategory("Payments").Never(); +logs.Verify().AtLevelOrAbove(LogLevel.Error).Never(); + +// One logger's category - the full name of its ILogger type, matched exactly: +logs.Verify() + .AtLevelOrAbove(LogLevel.Error) + .InCategory("MyApp.Payments.PaymentGateway") + .Never(); ``` `AddComponoCapture` returns the same builder, so it chains; it also works @@ -153,8 +159,21 @@ Every `CapturedLogEntry` carries `Category`: built-ins). - Non-generic `CapturingLogger` and a bare composed `ILogger`: `""`. -`InCategory` is exact, ordinal, case-sensitive. For prefix/wildcard -matching use `.Matching(entry => ...)`. +`InCategory` is exact, ordinal, case-sensitive: `InCategory("MyApp.Payments")` +does **not** match an entry whose category is +`MyApp.Payments.PaymentGateway`. This differs from the host's own filter +rules — `AddFilter("MyApp.Payments", ...)` and `Logging:LogLevel:MyApp.Payments` +configuration match every category that *starts with* that prefix. Combined +with `Never()`, a category string that matches nothing passes without +checking anything, so use the full category name, or assert by prefix +explicitly: + +```csharp +logs.Verify() + .AtLevelOrAbove(LogLevel.Error) + .Matching(entry => entry.Category.StartsWith("MyApp.Payments.", StringComparison.Ordinal)) + .Never(); +``` > **Behavioral compatibility note.** `Category` is part of > `CapturedLogEntry`'s record value equality: two entries identical in @@ -173,8 +192,10 @@ composed `logger.Verify()` and a `LogCollector.Verify()`: - `.InCategory(category)` — exact ordinal match; `null` throws `ArgumentNullException`. -Both produce readable failure text, e.g. `a log entry matching level Error -or above`, `a log entry matching category "Payments"`. +Both contribute to the failure text, e.g. `Expected exactly 0 call(s) to a +log entry matching level Error or above, but received 1.` The message +names the filters and the match count only — it does not list the matching +entries. Read them with `GetCapturedEntries()` when diagnosing a failure. ### Host filtering still applies @@ -185,21 +206,19 @@ level if you need them: ```csharp builder.Logging.SetMinimumLevel(LogLevel.Trace); -// or a category rule: -builder.Logging.AddFilter("Payments", LogLevel.Debug); +// or a category rule (prefix match: covers MyApp.Payments.*): +builder.Logging.AddFilter("MyApp.Payments", LogLevel.Debug); ``` -On net10.0/net11.0 the provider carries `[ProviderAlias("Compono")]`, so a -provider-specific rule works too: +The provider is registered under the `Compono` alias, so a rule that +targets only the Compono provider works on every supported target +framework (net8.0 through net11.0): ```json { "Logging": { "Compono": { "LogLevel": { "Default": "Warning" } } } } ``` -`LogLevel.None` is never captured on any target framework. On net8.0/net9.0 -the alias attribute is unavailable from `Logging.Abstractions` alone -(documented in ADR-0071 Amendment 1); use `SetMinimumLevel`/`AddFilter` -there. +`LogLevel.None` is never captured on any target framework. ### Host vs. composed: separate destinations @@ -226,15 +245,39 @@ through the collector instead. Opt-in forwarding is deferred. still returns a usable disposable); entries captured before disposal remain, and `ClearCapturedEntries()` still works. - Registering the **same** collector twice on one builder is idempotent: - one provider, one copy of each entry. Different collectors on one builder + one provider, one copy of each entry. Duplicate detection follows the + provider registrations themselves, so after `ClearProviders()` removes + the provider, registering the same collector again adds it back. Different collectors on one builder each get their own provider and both receive every entry. The same collector across several hosts receives entries from all of them; disposing one host stops only that host. - One private lock per collector guards appends, clears, and reads; reads return snapshots. There is no static/ambient state, so parallel tests with their own hosts and collectors do not interfere. +- Scopes come from the host's shared scope provider, not per logger: a + scope opened with `BeginScope` on one host logger also appears in the + `Scopes` of entries other categories log inside it on the same async + flow — the standard `Microsoft.Extensions.Logging` behavior. Composed + loggers keep a per-logger scope stack instead. - Activity scopes configured through `LoggerFactoryOptions .ActivityTrackingOptions` appear in `Scopes` like any other scope. +- The collector keeps every entry until you call `ClearCapturedEntries()`; + there is no size limit. A collector shared by many tests (for example a + `WebApplicationFactory` fixture) accumulates entries across them — clear + it at the start of each test, or give each test its own collector. + +### When nothing is captured + +Capture relies on the host's `ILoggerFactory` dispatching to registered +`ILoggerProvider`s. A host that **replaces** `ILoggerFactory` with one that +ignores registered providers bypasses the collector entirely — for +example Serilog's `UseSerilog()` without `writeToProviders: true`. Then +`Never()` passes because nothing was captured, not because nothing was +logged. Likewise, a `ClearProviders()` call that runs *after* +`AddComponoCapture` (for example in the application's own startup code) +removes the Compono provider. When in doubt, assert that the collector saw +something you know the host logs, such as the `Microsoft.Hosting.Lifetime` +"Application started" entry after `StartAsync`. ## Structured properties and `MessageTemplate` diff --git a/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md b/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md index 4b505fbf..84af052f 100644 --- a/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md +++ b/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md @@ -738,3 +738,64 @@ python3 -c "import json;json.load(open('skills/compono/evals/evals.json'))" and clears. Re-ran focused logging tests (514 passed/0 failed per TFM), full build 0/0, full suite 7057 total/0 failed, and the AOT logging leg (PASS, zero IL warnings). + +- 2026-11-11 (independent review remediation, PR #177): a second review round + raised seven findings; disposition below. Nothing here is merged yet — PR + #177 is still open for maintainer review. + + - **F1 — confirmed registration defect (fixed).** Registering a collector, + calling `ClearProviders()`, then registering the *same* collector silently + stopped capturing: the old per-collector guard relied on a separate + registration-marker descriptor that `ClearProviders()` does not remove, so + the re-registration was treated as a duplicate while its provider was gone. + Fix: `ComponoCaptureRegistration` is no longer a standalone marker service; + it now exposes an instance method whose delegate target *is* the live + registration, and `IsAlreadyRegistered` scans the current + `ILoggerProvider` descriptors for that factory target (identity by + collector reference). Regression tests added to + `test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs`: + `ClearProvidersThenReRegisteringTheSameCollector_StillCaptures`, + `ClearProvidersThenReRegisteringTwice_StaysIdempotent`, + `ClearProvidersThenRegisteringADifferentCollector_OnlyTheNewCollectorCaptures`, + `SameCollectorOnIndependentServiceCollections_IsNotTreatedAsADuplicate`. + - **F2 — provider-alias availability (fixed, ADR-0071 Amendment 2).** The + `Compono` provider alias was unavailable on net8.0/net9.0 because + `ProviderAliasAttribute` only exists in `Logging.Abstractions` for + net10.0+. The attribute is now applied unconditionally and an internal + same-full-name copy (`src/Compono.Logging/ProviderAliasAttribute.cs`, under + `#if !NET10_0_OR_GREATER`) is compiled for the older TFMs; MEL resolves the + alias by full type name, so the copy is honored. No new package + dependencies; `CS0436` is promoted to an error in + `Compono.Logging.csproj` so a consumer-visible type collision cannot slip + through. Recorded as ADR-0071 Amendment 2 (2026-11-11); Amendment 1's + historical text is unchanged. + - **F3/F4/F5/F6 — documentation corrections.** `InCategory` is exact + ordinal full-type-name matching, *not* prefix matching like `AddFilter` + (so `.InCategory("Payments")` matches nothing in a real host; use + `.Matching(e => e.Category.StartsWith(...))` for namespaces). `Never()`'s + failure message names the filters and match count but does **not** include + the matching entries. A shared `WebApplicationFactory` collector retains + entries across tests until explicitly cleared. A third-party + `ILoggerFactory` replacement (or a post-registration `ClearProviders()`) + can bypass the registered `ILoggerProvider`s and yield an empty capture. + Updated `docs/packages/compono-logging.md`, + `docs/how-to/assert-nothing-logged-at-error-across-a-host.md`, + `docs/troubleshooting/common-errors.md` + `index.md`, + `skills/compono/references/logging.md`, and evals #63/#64. + - **F7 — deferred.** AOT warnings are not universally promoted to errors in + this repo (a pre-existing repo-wide policy gap, not specific to this PR). + Left out of scope here. + - Validation: `dotnet build Compono.slnx -c Release` 0 warnings/0 errors; + full suite green (7087 total, 0 failed, 6586 succeeded, 501 skipped) with + the focused logging suite at 544/0. ApiCompat (V6): `Compono.Logging` + packs against the `1.4.0-preview.125` baseline with no `CP` errors + (additions only). V7 packed-nupkg inspection passes and the packed + dependency groups are unchanged. Pack-and-consume (F2): a multi-target + (`net8.0;net9.0;net10.0;net11.0`) consumer restored from a local feed + packed from this worktree (sha512 verified) builds 0/0 with `CS0436`/ + `CS0104` as errors and runs on every TFM — `Logging:Compono:LogLevel:Default` + filters the Compono provider, an unrelated provider is unaffected, and a + consumer-defined `ProviderAliasAttribute` use compiles unambiguously. + AOT for the net8.0/net9.0 legs (not covered by CI's net10.0-only publish) + was verified locally: `PublishAot` osx-arm64 binaries built with zero + IL2xxx/IL3xxx warnings and ran, honoring the alias. diff --git a/docs/troubleshooting/common-errors.md b/docs/troubleshooting/common-errors.md index 02ce153c..581a99f2 100644 --- a/docs/troubleshooting/common-errors.md +++ b/docs/troubleshooting/common-errors.md @@ -324,11 +324,32 @@ builder.Logging.SetMinimumLevel(LogLevel.Trace); ``` The same happens when a configured category rule or `AddFilter` excludes -the category. On .NET 10 and later you can also target only the Compono -provider with the `Compono` alias, for example -`Logging:Compono:LogLevel:Default`. On .NET 8 and 9 the alias is not -available from the shipped `Logging.Abstractions` dependency (ADR-0071 -Amendment 1); use the global minimum level or `AddFilter` there instead. +the category. To target only the Compono provider, use its `Compono` +alias, for example `Logging:Compono:LogLevel:Default` — this works on every +supported target framework. + +### "`Never()` passes but the host clearly logged an error" + +`Never()` passes whenever no captured entry matches, including when the +filter matches nothing or the collector captured nothing at all: + +- **`InCategory` was given a prefix or short name.** It is an exact match + on the full category (normally the `ILogger` type's full name), unlike + `AddFilter`/`Logging:LogLevel:*` rules, which match by prefix. Use the + full name, or + `.Matching(entry => entry.Category.StartsWith("MyApp.Payments.", StringComparison.Ordinal))`. +- **The host replaced `ILoggerFactory`.** A logging library that swaps in + its own factory and ignores registered providers — for example Serilog's + `UseSerilog()` without `writeToProviders: true` — never calls the + Compono provider. +- **The provider was removed after registration.** Application code that + calls `ClearProviders()` after the test's `AddComponoCapture` removes it. + Register the collector after that code runs (for `WebApplicationFactory`, + in `ConfigureWebHost`). + +Check that the collector captured something you know the host logs, such +as `logs.Verify().InCategory("Microsoft.Hosting.Lifetime").AtLeast(1)` after +`StartAsync`. ### "Two composed parameters of the same type aren't the same instance" diff --git a/docs/troubleshooting/index.md b/docs/troubleshooting/index.md index 44a5a9b4..2b98f9c0 100644 --- a/docs/troubleshooting/index.md +++ b/docs/troubleshooting/index.md @@ -11,8 +11,9 @@ than reading top to bottom. at runtime**, with no `CMP` code → [Common Errors: Runtime Composition Failures](common-errors.md#runtime-composition-failures). - **A `LogCollector` assertion doesn't see entries you expected** (a host - `ILogger` throws from `Verify()`, or `Debug`/`Trace` entries are - missing) → [Common Errors: Host-wide logging](common-errors.md#verify-on-a-host-iloggert-throws). + `ILogger` throws from `Verify()`, `Debug`/`Trace` entries are + missing, or `Never()` passes although the host logged an error) → + [Common Errors: Host-wide logging](common-errors.md#verify-on-a-host-iloggert-throws). - **Something works but doesn't behave the way you expected** (a value looks wrong, a substitute doesn't do what you thought, a value isn't shared) → [FAQ](faq.md). diff --git a/skills/compono/evals/evals.json b/skills/compono/evals/evals.json index 0cad0d6b..6d28e2ed 100644 --- a/skills/compono/evals/evals.json +++ b/skills/compono/evals/evals.json @@ -782,6 +782,33 @@ "Does not suggest registering UseLogging() on the host, casting/unwrapping the host logger, or a nonexistent forwarding option", "Does not claim host-wide capture is unsupported" ] + }, + { + "id": 63, + "category": "behavioral-correctness", + "prompt": "I registered a LogCollector with AddComponoCapture on my Generic Host. My services live in the MyApp.Payments namespace (for example ILogger). I wrote logs.Verify().AtLevelOrAbove(LogLevel.Error).InCategory(\"MyApp.Payments\").Never() and it passes, but I can see PaymentGateway logging errors. Why, and how should I assert no errors from anything in that namespace?", + "expected_output": "InCategory is an exact, ordinal, case-sensitive match on CapturedLogEntry.Category, and a host ILogger's category is the type's full name (MyApp.Payments.PaymentGateway), so InCategory(\"MyApp.Payments\") matches no entry and Never() passes without checking anything. This differs from the host's own AddFilter/Logging:LogLevel rules, which match by category prefix. Use the full category name for one logger, or for a namespace use Matching(entry => entry.Category.StartsWith(\"MyApp.Payments.\", StringComparison.Ordinal)).Never(). Optionally add a sanity assertion that the collector captured something expected.", + "files": [], + "expectations": [ + "Explains InCategory is an exact match, not a prefix match, so a namespace string matches nothing", + "Explains Never() therefore passes without checking anything", + "Contrasts this with AddFilter/configuration category rules, which match by prefix", + "Recommends the full category name for one logger, or Matching(entry => entry.Category.StartsWith(...)) for a namespace", + "Does not claim InCategory supports wildcards or prefixes, and does not invent a new filter method" + ] + }, + { + "id": 64, + "category": "behavioral-correctness", + "prompt": "My test project targets net8.0 and references Compono.Logging. I want my LogCollector to see Debug entries without changing what my other logging providers receive. Can I use a Logging:Compono configuration rule on net8.0, or is that .NET 10+ only?", + "expected_output": "Yes - the Compono provider is registered under the Compono alias on every supported target framework (net8.0 through net11.0), so a rule such as Logging:Compono:LogLevel:Default = Debug (plus a global minimum low enough for Debug to reach the providers, or a per-provider rule) applies only to the Compono provider. It is not .NET 10+ only. AddComponoCapture itself never changes filter rules; the host's LoggerFilterOptions decides what reaches the collector.", + "files": [], + "expectations": [ + "States the Logging:Compono provider-alias rule works on net8.0 (every supported TFM), not only on .NET 10+", + "Shows a Logging:Compono:LogLevel configuration rule targeting only the Compono provider", + "States AddComponoCapture does not change filter rules - the host's filter configuration decides what is captured", + "Does not suggest referencing the internal provider type name or adding a dependency to get the alias" + ] } ] } diff --git a/skills/compono/references/logging.md b/skills/compono/references/logging.md index f357c494..15807b99 100644 --- a/skills/compono/references/logging.md +++ b/skills/compono/references/logging.md @@ -131,7 +131,12 @@ builder.Logging.ClearProviders(); builder.Logging.AddComponoCapture(logs); using var host = builder.Build(); -logs.Verify().AtLevelOrAbove(LogLevel.Error).InCategory("Payments").Never(); +logs.Verify().AtLevelOrAbove(LogLevel.Error).Never(); +// One category: the ILogger type's FULL name, matched exactly. +logs.Verify().AtLevelOrAbove(LogLevel.Error).InCategory("MyApp.Payments.PaymentGateway").Never(); +// A namespace: match the prefix explicitly. +logs.Verify().AtLevelOrAbove(LogLevel.Error) + .Matching(e => e.Category.StartsWith("MyApp.Payments.", StringComparison.Ordinal)).Never(); ``` Key semantics to get right: @@ -140,7 +145,15 @@ Key semantics to get right: `ILoggerProvider.CreateLogger` string; composed/direct `CapturingLogger` matches `LoggerFactory.CreateLogger()`; non-generic `CapturingLogger` and a bare composed `ILogger` carry `""`. `InCategory` is exact, ordinal, - case-sensitive — use `.Matching(...)` for prefixes. + case-sensitive — **not** a prefix match, unlike the host's own + `AddFilter`/`Logging:LogLevel:*` rules. Never write + `InCategory("Payments")`/a namespace with `.Never()`: it matches nothing + and passes without checking anything. Use the full category name or + `.Matching(e => e.Category.StartsWith(...))`. +- `Never()`'s failure text names the filters and the match count only + (`Expected exactly 0 call(s) to a log entry matching level Error or + above, but received 1.`); it does not list entries — read them with + `GetCapturedEntries()`. - **Behavioral change**: `Category` participates in the record's value equality. Entries differing only by category are not equal. This is intentional (ADR-0071), not a bug to "fix." @@ -153,15 +166,27 @@ Key semantics to get right: - The host's own filters still apply: default minimum `Information` means `Debug`/`Trace` are not captured; lower it with `builder.Logging.SetMinimumLevel(LogLevel.Trace)` or `AddFilter`. - `AddComponoCapture` never changes filter rules. On net10/net11 a - `Logging:Compono:LogLevel` provider-alias rule also works; on net8/net9 - it does not (ADR-0071 Amendment 1). + `AddComponoCapture` never changes filter rules. A + `Logging:Compono:LogLevel:*` provider-alias rule targets only the + Compono provider, on every supported TFM (net8.0–net11.0; ADR-0071 + Amendment 2 — don't repeat the old "net10+ only" caveat). - The test owns the collector; the host owns the provider. Disposing the host stops capture but never clears the collector — entries stay readable and `ClearCapturedEntries()` still works. Registering the same - collector twice is idempotent; different collectors each receive every - entry; one collector across hosts receives all (disposing one host stops - only that host). + collector twice is idempotent (and re-registering after `ClearProviders()` + adds it back); different collectors each receive every entry; one + collector across hosts receives all (disposing one host stops only that + host). +- No size limit: the collector keeps everything until + `ClearCapturedEntries()`. A `WebApplicationFactory`/class-fixture + collector is shared across tests — clear it at the start of each test. +- Host scopes come from the host's shared scope provider, so a scope opened + on one host logger also appears on entries other categories log inside it. +- A vacuous pass is the main risk: if the app replaces `ILoggerFactory` + (e.g. Serilog `UseSerilog()` without `writeToProviders: true`) or calls + `ClearProviders()` after the test's registration, nothing is captured + and `Never()` passes. Suggest a sanity assertion such as + `logs.Verify().InCategory("Microsoft.Hosting.Lifetime").AtLeast(1)`. ## Structured properties and `MessageTemplate` diff --git a/src/Compono.Logging/Compono.Logging.csproj b/src/Compono.Logging/Compono.Logging.csproj index 3b0bb1d5..74adf90c 100644 --- a/src/Compono.Logging/Compono.Logging.csproj +++ b/src/Compono.Logging/Compono.Logging.csproj @@ -12,6 +12,12 @@ 1 for why this claim is now backed by generated closed-generic activation rather than the originally-assumed "member surface is fixed and small" reasoning alone. --> true + + $(WarningsAsErrors);CS0436 diff --git a/src/Compono.Logging/ComponoCaptureRegistration.cs b/src/Compono.Logging/ComponoCaptureRegistration.cs index 571ebed8..7790b99c 100644 --- a/src/Compono.Logging/ComponoCaptureRegistration.cs +++ b/src/Compono.Logging/ComponoCaptureRegistration.cs @@ -1,11 +1,17 @@ +using Microsoft.Extensions.Logging; + namespace Compono.Logging; /// -/// DI registration marker for - its -/// presence in the service collection is how a repeated registration of the same -/// is detected and made idempotent, without the distinct-collector-dropping -/// behavior a naive TryAddEnumerable (dedup by implementation type) would cause. Internal - -/// purely a registration detail. See docs/adr/0071-compono-logging-host-wide-log-capture.md. +/// The owner of one registration - +/// its method is the descriptor's +/// implementation factory, so the descriptor itself identifies which it +/// captures into. That is how a repeated registration of the same collector is detected and made +/// idempotent: detection inspects the live provider descriptors, so a ClearProviders() +/// (which removes them) also removes the duplicate-detection state, and a later re-registration is +/// honored. A naive TryAddEnumerable (dedup by implementation type) would instead drop a +/// second, distinct collector. Internal - purely a registration detail. See +/// docs/adr/0071-compono-logging-host-wide-log-capture.md. /// internal sealed class ComponoCaptureRegistration { @@ -15,4 +21,9 @@ public ComponoCaptureRegistration(LogCollector collector) } public LogCollector Collector { get; } + + // An instance method (not a lambda) so the registered delegate's Target is this registration - + // ComponoLoggingBuilderExtensions reads it back to detect a duplicate. The container still + // creates, owns, and disposes the provider (ADR-0071 "Ownership, lifetime, disposal"). + public ILoggerProvider CreateProvider(IServiceProvider services) => new ComponoLogCollectorProvider(Collector); } diff --git a/src/Compono.Logging/ComponoLogCollectorProvider.cs b/src/Compono.Logging/ComponoLogCollectorProvider.cs index 336fc79d..301e761c 100644 --- a/src/Compono.Logging/ComponoLogCollectorProvider.cs +++ b/src/Compono.Logging/ComponoLogCollectorProvider.cs @@ -9,15 +9,13 @@ namespace Compono.Logging; /// so a logger's scopes come from the host's own scope provider /// (falling back to its own only if the host never supplies /// one). Never public - a consumer reaches capture through . See -/// docs/adr/0071-compono-logging-host-wide-log-capture.md and its Amendment 1. +/// docs/adr/0071-compono-logging-host-wide-log-capture.md and its Amendment 2. /// -// ProviderAliasAttribute only lives in Logging.Abstractions on net10.0+; on net8.0/net9.0 it is in -// the Microsoft.Extensions.Logging implementation package, which ADR-0071 deliberately doesn't -// reference. ADR-0071 Amendment 1 therefore scopes the alias (and the Logging:Compono:* config rule -// it enables) to net10.0/net11.0 so the shipped dependency graph stays Abstractions-only. -#if NET10_0_OR_GREATER +// On net10.0/net11.0 this is the real attribute from Logging.Abstractions; on net8.0/net9.0 it is +// the internal, same-full-name copy in ProviderAliasAttribute.cs (the logging framework matches the +// alias by full type name), so the Logging:Compono:* rule works on every target framework while the +// shipped dependency graph stays Abstractions-only (ADR-0071 Amendment 2). [ProviderAlias("Compono")] -#endif internal sealed class ComponoLogCollectorProvider : ILoggerProvider, ISupportExternalScope { private readonly LogCollector _collector; diff --git a/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs b/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs index 169e6904..32356f70 100644 --- a/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs +++ b/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs @@ -30,17 +30,21 @@ public static ILoggingBuilder AddComponoCapture(this ILoggingBuilder builder, Lo if (IsAlreadyRegistered(builder.Services, collector)) return builder; - builder.Services.Add(ServiceDescriptor.Singleton(new ComponoCaptureRegistration(collector))); - builder.Services.Add(ServiceDescriptor.Singleton(_ => new ComponoLogCollectorProvider(collector))); + var registration = new ComponoCaptureRegistration(collector); + builder.Services.Add(ServiceDescriptor.Singleton(registration.CreateProvider)); return builder; } + // Inspects the live ILoggerProvider descriptors themselves (not a separate marker service), so + // ClearProviders()/RemoveAll() also clears the duplicate-detection state. private static bool IsAlreadyRegistered(IServiceCollection services, LogCollector collector) { foreach (var descriptor in services) { - if (descriptor.ServiceType == typeof(ComponoCaptureRegistration) - && descriptor.ImplementationInstance is ComponoCaptureRegistration registration + // IsKeyedService is checked first: ImplementationFactory throws on a keyed descriptor. + if (descriptor.ServiceType == typeof(ILoggerProvider) + && !descriptor.IsKeyedService + && descriptor.ImplementationFactory?.Target is ComponoCaptureRegistration registration && ReferenceEquals(registration.Collector, collector)) { return true; diff --git a/src/Compono.Logging/ProviderAliasAttribute.cs b/src/Compono.Logging/ProviderAliasAttribute.cs new file mode 100644 index 00000000..f6f489e1 --- /dev/null +++ b/src/Compono.Logging/ProviderAliasAttribute.cs @@ -0,0 +1,33 @@ +#if !NET10_0_OR_GREATER +// net8.0/net9.0 only. Compono.Logging pins Microsoft.Extensions.Logging.Abstractions to the 8.x/9.x +// line on these targets, and ProviderAliasAttribute only moved into Abstractions in 10.x (before +// that it lived in the Microsoft.Extensions.Logging implementation package, which this package +// deliberately doesn't reference). On net10.0/net11.0 the real attribute from Abstractions is used +// instead, so this file compiles to nothing there. +// +// This internal copy works because Microsoft.Extensions.Logging resolves a provider's alias by the +// attribute's *full type name* ("Microsoft.Extensions.Logging.ProviderAliasAttribute") through +// CustomAttributeData, never by type identity - so it must keep exactly this namespace and name. +// Being internal, it is invisible to consumers and cannot collide with the public attribute in +// their compilation. If an Abstractions 10.x+ reference ever reaches these targets, the compiler +// reports the duplicate (CS0436), which Compono.Logging.csproj promotes to an error - a hard build +// failure rather than a silent change. See docs/adr/0071-compono-logging-host-wide-log-capture.md +// Amendment 2. +namespace Microsoft.Extensions.Logging; + +/// +/// Internal net8.0/net9.0 stand-in for Microsoft.Extensions.Logging.ProviderAliasAttribute, so +/// 's Compono alias works on every +/// target framework without an implementation-package dependency (ADR-0071 Amendment 2). +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] +internal sealed class ProviderAliasAttribute : Attribute +{ + public ProviderAliasAttribute(string alias) + { + Alias = alias; + } + + public string Alias { get; } +} +#endif diff --git a/test/Compono.Logging.AotSmokeTest/Program.cs b/test/Compono.Logging.AotSmokeTest/Program.cs index 0b6e5f4e..08077577 100644 --- a/test/Compono.Logging.AotSmokeTest/Program.cs +++ b/test/Compono.Logging.AotSmokeTest/Program.cs @@ -52,6 +52,7 @@ private static int Main() VerifyHostWideCapture(); VerifyCategoryParityUnderAot(); + VerifyProviderAliasRuleUnderAot(); Console.WriteLine( "PASS: UseLogging()-composed ILogger (generator-discovered activation), " + @@ -99,6 +100,28 @@ private static void VerifyHostWideCapture() collector.Verify().AtLevelOrAbove(LogLevel.Error).Never(); } + private static void VerifyProviderAliasRuleUnderAot() + { + // ADR-0071 Amendment 2: the logging framework resolves [ProviderAlias("Compono")] by the + // attribute's full type name via CustomAttributeData - prove that metadata survives Native + // AOT and a Logging:Compono:* rule actually filters the Compono provider. + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Configuration["Logging:Compono:LogLevel:Default"] = "Error"; + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + using var host = builder.Build(); + var logger = host.Services.GetRequiredService().CreateLogger("Alias.Smoke"); + + logger.LogWarning("below the Compono alias minimum"); + logger.LogError("meets the Compono alias minimum"); + + var entries = collector.GetCapturedEntries(); + if (entries.Count != 1 || entries[0].LogLevel != LogLevel.Error) + throw new InvalidOperationException( + $"Expected the Logging:Compono rule to keep only the Error entry, got {entries.Count} entries."); + } + private static void VerifyCategoryParityUnderAot() { // Compare against the real LoggerFactory's own category, never a hard-coded string - this diff --git a/test/Compono.Logging.Tests/HostLogCaptureTests.cs b/test/Compono.Logging.Tests/HostLogCaptureTests.cs index d8c4dd24..d6781691 100644 --- a/test/Compono.Logging.Tests/HostLogCaptureTests.cs +++ b/test/Compono.Logging.Tests/HostLogCaptureTests.cs @@ -204,13 +204,11 @@ public void HostCategoryFilter_ExcludesFilteredEntries() entries.Should().NotContain(entry => entry.Message == "excluded"); } -#if NET10_0_OR_GREATER [Fact] public void ProviderAliasConfiguration_AppliesProviderSpecificRuleToComponoProvider() { - // ADR-0071 Amendment 1: [ProviderAlias("Compono")] lives in Logging.Abstractions only on - // net10.0+, so this provider-specific configuration rule is a net10/net11 capability; net8 - // and net9 use the global minimum level/AddFilter rules exercised above. + // ADR-0071 Amendment 2: the "Compono" alias works on every target framework - the real + // attribute on net10/net11, the internal same-full-name copy on net8/net9. var collector = new LogCollector(); var builder = Host.CreateApplicationBuilder(); builder.Configuration["Logging:Compono:LogLevel:Default"] = "Warning"; @@ -226,7 +224,53 @@ public void ProviderAliasConfiguration_AppliesProviderSpecificRuleToComponoProvi entries.Should().ContainSingle(); entries[0].Message.Should().Be("meets alias minimum"); } -#endif + + [Fact] + public void ProviderAliasCategoryRule_AppliesOnlyToTheMatchingCategoryPrefix() + { + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Configuration["Logging:Compono:LogLevel:Noisy"] = "Error"; + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + using var host = builder.Build(); + var factory = host.Services.GetRequiredService(); + + factory.CreateLogger("Noisy.Component").LogWarning("filtered by the Compono alias prefix rule"); + factory.CreateLogger("Quiet.Component").LogWarning("unaffected category"); + + collector.GetCapturedEntries().Should().ContainSingle().Which.Message.Should().Be("unaffected category"); + } + + [Fact] + public void ProviderAliasRule_DoesNotAffectOtherProviders() + { + var collector = new LogCollector(); + var other = new RecordingProvider(); + var builder = Host.CreateApplicationBuilder(); + builder.Configuration["Logging:Compono:LogLevel:Default"] = "Error"; + builder.Logging.ClearProviders(); + builder.Logging.AddProvider(other); + builder.Logging.AddComponoCapture(collector); + using var host = builder.Build(); + + host.Services.GetRequiredService().CreateLogger("Shared.Category").LogWarning("warning"); + + collector.GetCapturedEntries().Should().BeEmpty(); + other.Count.Should().Be(1); + } + + [Fact] + public void ComponoProvider_CarriesTheComponoAliasByFullAttributeName() + { + // The logging framework resolves aliases by the attribute's full type name, so pin that + // name (not just the alias behavior) on every target framework. + var alias = typeof(ComponoLogCollectorProvider) + .GetCustomAttributesData() + .Single(attribute => attribute.AttributeType.FullName == "Microsoft.Extensions.Logging.ProviderAliasAttribute"); + + alias.ConstructorArguments.Should().ContainSingle().Which.Value.Should().Be("Compono"); + } [Fact] public void LogLevelNone_IsNeverCaptured() @@ -411,3 +455,32 @@ private static IHost CreateHost(LogCollector collector) return builder.Build(); } } + +internal sealed class RecordingProvider : ILoggerProvider +{ + private int _count; + + public int Count => Volatile.Read(ref _count); + + public ILogger CreateLogger(string categoryName) => new RecordingLogger(this); + + public void Dispose() + { + } + + private sealed class RecordingLogger(RecordingProvider owner) : ILogger + { + public IDisposable? BeginScope(TState state) + where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) => + Interlocked.Increment(ref owner._count); + } +} diff --git a/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs b/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs index d7cebf4c..ae316bbc 100644 --- a/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs +++ b/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs @@ -22,6 +22,83 @@ public void SameCollectorRegisteredTwice_ProducesOneProviderAndOneCopyOfEachEntr collector.GetCapturedEntries().Should().ContainSingle(); } + [Fact] + public void ClearProvidersThenReRegisteringTheSameCollector_StillCaptures() + { + // Regression (PR #177 review): duplicate detection must track the live ILoggerProvider + // registration, not a separate marker that ClearProviders() leaves behind - otherwise the + // second AddComponoCapture is silently skipped and Never() passes without capturing anything. + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.AddComponoCapture(collector); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + using var host = builder.Build(); + + host.Services.GetRequiredService().CreateLogger("Cleared.Category").LogError("after re-registration"); + + host.Services.GetServices().OfType().Should().ContainSingle(); + collector.GetCapturedEntries().Should().ContainSingle().Which.Message.Should().Be("after re-registration"); + collector.Verify().AtLevelOrAbove(LogLevel.Error).InCategory("Cleared.Category").Once(); + var act = () => collector.Verify().AtLevelOrAbove(LogLevel.Error).Never(); + act.Should().Throw(); + } + + [Fact] + public void ClearProvidersThenReRegisteringTwice_StaysIdempotent() + { + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.AddComponoCapture(collector); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(collector); + builder.Logging.AddComponoCapture(collector); + using var host = builder.Build(); + + host.Services.GetRequiredService().CreateLogger("Cleared.Category").LogInformation("once"); + + host.Services.GetServices().OfType().Should().ContainSingle(); + collector.GetCapturedEntries().Should().ContainSingle(); + } + + [Fact] + public void ClearProvidersThenRegisteringADifferentCollector_OnlyTheNewCollectorCaptures() + { + var cleared = new LogCollector(); + var replacement = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.AddComponoCapture(cleared); + builder.Logging.ClearProviders(); + builder.Logging.AddComponoCapture(replacement); + using var host = builder.Build(); + + host.Services.GetRequiredService().CreateLogger("Cleared.Category").LogWarning("replacement only"); + + cleared.GetCapturedEntries().Should().BeEmpty(); + replacement.GetCapturedEntries().Should().ContainSingle().Which.Message.Should().Be("replacement only"); + } + + [Fact] + public void SameCollectorOnIndependentServiceCollections_IsNotTreatedAsADuplicate() + { + var collector = new LogCollector(); + var first = Host.CreateApplicationBuilder(); + var second = Host.CreateApplicationBuilder(); + first.Logging.ClearProviders(); + second.Logging.ClearProviders(); + first.Logging.AddComponoCapture(collector); + second.Logging.AddComponoCapture(collector); + using var firstHost = first.Build(); + using var secondHost = second.Build(); + + firstHost.Services.GetServices().OfType().Should().ContainSingle(); + secondHost.Services.GetServices().OfType().Should().ContainSingle(); + firstHost.Services.GetRequiredService().CreateLogger("First").LogError("from first"); + secondHost.Services.GetRequiredService().CreateLogger("Second").LogError("from second"); + + collector.Verify().AtLevelOrAbove(LogLevel.Error).Exactly(2); + } + [Fact] public void DifferentCollectorsOnOneBuilder_EachReceivesEveryEntry() { From 52dc39e8d522d465bc00ac922afc2df59e390c42 Mon Sep 17 00:00:00 2001 From: Nick Cipollina Date: Wed, 11 Nov 2026 09:55:46 -0500 Subject: [PATCH 6/6] docs(logging): fix host-capture sanity check and guard keyed providers The capture sanity assertion must be host-aware: a Generic Host on its default lifetime logs Microsoft.Hosting.Lifetime on StartAsync, but WebApplicationFactory/TestHost uses a different host lifetime and a shared fixture may clear startup entries between tests, so that assertion is unreliable there. Recommend a deterministic application-owned entry for WebApplicationFactory, and update the how-to, package guide, troubleshooting entry, skill reference, and evals. Add a keyed ILoggerProvider regression test proving AddComponoCapture still captures and does not throw. While verifying, correct the IsAlreadyRegistered comment: on supported runtimes a keyed descriptor's ImplementationFactory is null rather than throwing, so the !IsKeyedService guard is defense in depth. --- ...t-nothing-logged-at-error-across-a-host.md | 34 +++++++++++++++---- docs/packages/compono-logging.md | 10 ++++-- ...-log-capture-and-dotnet-11-ga-impl-plan.md | 29 ++++++++++++++++ docs/troubleshooting/common-errors.md | 10 ++++-- skills/compono/evals/evals.json | 16 ++++++++- skills/compono/references/logging.md | 10 ++++-- .../ComponoLoggingBuilderExtensions.cs | 5 ++- .../LogCollectorRegistrationTests.cs | 31 +++++++++++++++++ 8 files changed, 129 insertions(+), 16 deletions(-) diff --git a/docs/how-to/assert-nothing-logged-at-error-across-a-host.md b/docs/how-to/assert-nothing-logged-at-error-across-a-host.md index f04329cf..caa4ce95 100644 --- a/docs/how-to/assert-nothing-logged-at-error-across-a-host.md +++ b/docs/how-to/assert-nothing-logged-at-error-across-a-host.md @@ -146,12 +146,34 @@ If the application replaces the host's `ILoggerFactory` with one that ignores registered providers — for example Serilog's `UseSerilog()` without `writeToProviders: true` — or calls `ClearProviders()` *after* the test registered the collector, nothing reaches the collector and `Never()` -passes without checking anything. Guard against that by also asserting -something you know the host logs: - -```csharp -logs.Verify().InCategory("Microsoft.Hosting.Lifetime").AtLeast(1); -``` +passes without checking anything. + +Guard against a silently-empty collector by asserting it saw a known entry. +What to assert depends on the host: + +- **Generic Host with its default lifetime.** After `StartAsync` the host + itself logs "Application started" under `Microsoft.Hosting.Lifetime`, so: + + ```csharp + logs.Verify().InCategory("Microsoft.Hosting.Lifetime").AtLeast(1); + ``` + +- **`WebApplicationFactory` / ASP.NET Core `TestHost`.** Don't depend on + framework startup logging: `TestHost` runs a different host lifetime, and + a shared fixture may clear startup entries between tests. Assert a + deterministic entry your own code emits during the operation under test + instead: + + ```csharp + // The code under test logs this while handling the request. + factory.Logs.Verify() + .Matching(entry => entry.Message.Contains("Checkout started")) + .AtLeast(1); + ``` + + If you prefer to assert on framework request diagnostics, first confirm + the exact category they log under for your logging configuration rather + than assuming one. ## See also diff --git a/docs/packages/compono-logging.md b/docs/packages/compono-logging.md index a6b3d20a..ddaa00a9 100644 --- a/docs/packages/compono-logging.md +++ b/docs/packages/compono-logging.md @@ -275,9 +275,13 @@ example Serilog's `UseSerilog()` without `writeToProviders: true`. Then `Never()` passes because nothing was captured, not because nothing was logged. Likewise, a `ClearProviders()` call that runs *after* `AddComponoCapture` (for example in the application's own startup code) -removes the Compono provider. When in doubt, assert that the collector saw -something you know the host logs, such as the `Microsoft.Hosting.Lifetime` -"Application started" entry after `StartAsync`. +removes the Compono provider. When in doubt, assert the collector saw a +known entry so an empty collector fails loudly. On a Generic Host with its +default lifetime, the `Microsoft.Hosting.Lifetime` "Application started" +entry after `StartAsync` works; under a `WebApplicationFactory`/ASP.NET +Core `TestHost`, prefer a deterministic entry your own code emits during +the operation under test — `TestHost` runs a different host lifetime, and a +shared fixture may clear startup entries between tests. ## Structured properties and `MessageTemplate` diff --git a/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md b/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md index 84af052f..330cbcda 100644 --- a/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md +++ b/docs/plans/0072-compono-logging-host-wide-log-capture-and-dotnet-11-ga-impl-plan.md @@ -799,3 +799,32 @@ python3 -c "import json;json.load(open('skills/compono/evals/evals.json'))" AOT for the net8.0/net9.0 legs (not covered by CI's net10.0-only publish) was verified locally: `PublishAot` osx-arm64 binaries built with zero IL2xxx/IL3xxx warnings and ran, honoring the alias. + +- 2026-11-11 (review round 2 corrections, PR #177): Claude's second read-only + review approved with two non-blocking follow-ups, both addressed. Still open + for maintainer review; not merged. + + - Capture sanity-check docs: `logs.Verify().InCategory("Microsoft.Hosting.Lifetime").AtLeast(1)` + is only valid for a Generic Host running its default lifetime. Under a + `WebApplicationFactory`/ASP.NET Core `TestHost` it is unreliable (different + host lifetime, and a shared fixture may clear startup entries between + tests), so it can fail even when capture is wired correctly. The + recommendation is now host-aware: keep the `Microsoft.Hosting.Lifetime` + assertion for a Generic Host, but for `WebApplicationFactory` assert a + deterministic application-owned entry emitted during the operation under + test. Updated the how-to, package guide, troubleshooting entry, and skill + logging reference; sharpened eval #63 and added eval #65. + - Keyed-provider regression: added + `KeyedProviderDescriptorPresent_DoesNotBreakRegistrationOrCapture` (a keyed + `ILoggerProvider` plus `AddComponoCapture` must still capture and must not + throw) and verified it on net8.0/net9.0/net10.0/net11.0. While proving it, + found the `IsAlreadyRegistered` comment was wrong: on supported runtimes a + keyed descriptor's `ImplementationFactory` is `null`, not throwing (it is + `KeyedImplementationFactory` that throws on a non-keyed descriptor), so the + `!IsKeyedService` guard is defense in depth rather than a throw guard. The + guard stays; its comment and the test comment were corrected to match. + - Validation: `dotnet build Compono.slnx -c Release` 0/0; `test/Compono.Logging.Tests` + 548 passed/0 failed (137 per TFM); full suite 7091 total/0 failed/6590 + succeeded/501 skipped; `mkdocs build --clean --strict` exit 0; API reference + no drift; `evals.json` parses (65 evals) and `quick_validate.py` reports + valid. No package/AOT-affecting change, so those gates were not re-run. diff --git a/docs/troubleshooting/common-errors.md b/docs/troubleshooting/common-errors.md index 581a99f2..10702f89 100644 --- a/docs/troubleshooting/common-errors.md +++ b/docs/troubleshooting/common-errors.md @@ -347,9 +347,13 @@ filter matches nothing or the collector captured nothing at all: Register the collector after that code runs (for `WebApplicationFactory`, in `ConfigureWebHost`). -Check that the collector captured something you know the host logs, such -as `logs.Verify().InCategory("Microsoft.Hosting.Lifetime").AtLeast(1)` after -`StartAsync`. +Check that the collector captured something a host of this kind logs. On a +Generic Host with its default lifetime, +`logs.Verify().InCategory("Microsoft.Hosting.Lifetime").AtLeast(1)` after +`StartAsync` confirms capture. Under a `WebApplicationFactory`/ASP.NET Core +`TestHost`, assert a deterministic entry your own code emits during the +operation under test instead — `TestHost` runs a different host lifetime, +and a shared fixture may clear startup entries between tests. ### "Two composed parameters of the same type aren't the same instance" diff --git a/skills/compono/evals/evals.json b/skills/compono/evals/evals.json index 6d28e2ed..31c2b041 100644 --- a/skills/compono/evals/evals.json +++ b/skills/compono/evals/evals.json @@ -787,7 +787,7 @@ "id": 63, "category": "behavioral-correctness", "prompt": "I registered a LogCollector with AddComponoCapture on my Generic Host. My services live in the MyApp.Payments namespace (for example ILogger). I wrote logs.Verify().AtLevelOrAbove(LogLevel.Error).InCategory(\"MyApp.Payments\").Never() and it passes, but I can see PaymentGateway logging errors. Why, and how should I assert no errors from anything in that namespace?", - "expected_output": "InCategory is an exact, ordinal, case-sensitive match on CapturedLogEntry.Category, and a host ILogger's category is the type's full name (MyApp.Payments.PaymentGateway), so InCategory(\"MyApp.Payments\") matches no entry and Never() passes without checking anything. This differs from the host's own AddFilter/Logging:LogLevel rules, which match by category prefix. Use the full category name for one logger, or for a namespace use Matching(entry => entry.Category.StartsWith(\"MyApp.Payments.\", StringComparison.Ordinal)).Never(). Optionally add a sanity assertion that the collector captured something expected.", + "expected_output": "InCategory is an exact, ordinal, case-sensitive match on CapturedLogEntry.Category, and a host ILogger's category is the type's full name (MyApp.Payments.PaymentGateway), so InCategory(\"MyApp.Payments\") matches no entry and Never() passes without checking anything. This differs from the host's own AddFilter/Logging:LogLevel rules, which match by category prefix. Use the full category name for one logger, or for a namespace use Matching(entry => entry.Category.StartsWith(\"MyApp.Payments.\", StringComparison.Ordinal)).Never(). Optionally add a sanity assertion that the collector captured a known entry, so a match-nothing filter can't pass silently - on a Generic Host with its default lifetime that can be the Microsoft.Hosting.Lifetime \"Application started\" entry after StartAsync, but under a WebApplicationFactory/ASP.NET Core TestHost it should be a deterministic entry the code under test emits (TestHost runs a different host lifetime and a shared fixture may clear startup entries between tests).", "files": [], "expectations": [ "Explains InCategory is an exact match, not a prefix match, so a namespace string matches nothing", @@ -809,6 +809,20 @@ "States AddComponoCapture does not change filter rules - the host's filter configuration decides what is captured", "Does not suggest referencing the internal provider type name or adding a dependency to get the alias" ] + }, + { + "id": 65, + "category": "behavioral-correctness", + "prompt": "My WebApplicationFactory test registers a LogCollector with AddComponoCapture and asserts factory.Logs.Verify().AtLevelOrAbove(LogLevel.Error).Never(). To make sure capture is actually wired up, I added factory.Logs.Verify().InCategory(\"Microsoft.Hosting.Lifetime\").AtLeast(1) first, but it fails even though the app is clearly logging. Is that the right sanity check?", + "expected_output": "Not under WebApplicationFactory. ASP.NET Core TestHost runs a different host lifetime than a Generic Host, and a shared fixture may clear startup entries between tests, so Microsoft.Hosting.Lifetime (and other framework startup logging) is not a reliable sanity check there. Prefer asserting a deterministic entry the code under test emits during the operation under test - for example factory.Logs.Verify().Matching(entry => entry.Message.Contains(\"Checkout started\")).AtLeast(1) - so a wired-up collector is proven by something the test itself caused. If you want framework request diagnostics, confirm the exact category they log under for your logging configuration first, rather than assuming one. On a Generic Host with its default lifetime, the Microsoft.Hosting.Lifetime \"Application started\" entry after StartAsync is a fine sanity check.", + "files": [], + "expectations": [ + "Explains that Microsoft.Hosting.Lifetime is not a reliable sanity check under WebApplicationFactory/ASP.NET Core TestHost", + "Attributes the unreliability to TestHost's different host lifetime and/or a shared fixture clearing startup entries between tests", + "Recommends asserting a deterministic application-owned entry emitted during the operation under test", + "Notes that the Generic Host default lifetime does log Microsoft.Hosting.Lifetime on StartAsync, so the category itself is not wrong", + "Does not suggest the collector is broken or that Never() is unreliable when capture is correctly wired" + ] } ] } diff --git a/skills/compono/references/logging.md b/skills/compono/references/logging.md index 15807b99..c5707757 100644 --- a/skills/compono/references/logging.md +++ b/skills/compono/references/logging.md @@ -185,8 +185,14 @@ Key semantics to get right: - A vacuous pass is the main risk: if the app replaces `ILoggerFactory` (e.g. Serilog `UseSerilog()` without `writeToProviders: true`) or calls `ClearProviders()` after the test's registration, nothing is captured - and `Never()` passes. Suggest a sanity assertion such as - `logs.Verify().InCategory("Microsoft.Hosting.Lifetime").AtLeast(1)`. + and `Never()` passes. Suggest a sanity assertion that the collector saw a + known entry. On a Generic Host with its default lifetime, + `logs.Verify().InCategory("Microsoft.Hosting.Lifetime").AtLeast(1)` after + `StartAsync` works; under a `WebApplicationFactory`/ASP.NET Core + `TestHost`, prefer a deterministic entry the code under test emits + (don't rely on framework startup logging — `TestHost` runs a different + host lifetime and a shared fixture may clear startup entries between + tests). ## Structured properties and `MessageTemplate` diff --git a/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs b/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs index 32356f70..600d46e0 100644 --- a/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs +++ b/src/Compono.Logging/ComponoLoggingBuilderExtensions.cs @@ -41,7 +41,10 @@ private static bool IsAlreadyRegistered(IServiceCollection services, LogCollecto { foreach (var descriptor in services) { - // IsKeyedService is checked first: ImplementationFactory throws on a keyed descriptor. + // Keyed descriptors are skipped: a keyed ILoggerProvider can never be a Compono + // registration. (On supported runtimes a keyed descriptor's ImplementationFactory is + // null rather than throwing, so this is defense in depth - but it keeps the intent + // explicit and stays correct if that behavior ever changes.) if (descriptor.ServiceType == typeof(ILoggerProvider) && !descriptor.IsKeyedService && descriptor.ImplementationFactory?.Target is ComponoCaptureRegistration registration diff --git a/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs b/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs index ae316bbc..345bb977 100644 --- a/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs +++ b/test/Compono.Logging.Tests/LogCollectorRegistrationTests.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; namespace Compono.Logging.Tests; @@ -132,6 +133,27 @@ public void SameCollectorAcrossTwoHosts_ReceivesEntriesFromBoth() collector.GetCapturedEntries().Should().Contain(entry => entry.Message == "from second"); } + [Fact] + public void KeyedProviderDescriptorPresent_DoesNotBreakRegistrationOrCapture() + { + // Regression (PR #177 round 2): IsAlreadyRegistered walks ILoggerProvider descriptors and + // reads ImplementationFactory. A keyed descriptor is skipped by the !IsKeyedService guard + // (its ImplementationFactory is null on supported runtimes), so a keyed ILoggerProvider + // registered before AddComponoCapture must neither throw nor stop capture. + var collector = new LogCollector(); + var builder = Host.CreateApplicationBuilder(); + builder.Logging.ClearProviders(); + builder.Services.AddKeyedSingleton("keyed", (_, _) => new NoOpLoggerProvider()); + builder.Logging.AddComponoCapture(collector); + using var host = builder.Build(); + + host.Services.GetRequiredService().CreateLogger("Keyed.Category").LogError("captured despite keyed provider"); + + host.Services.GetServices().OfType().Should().ContainSingle(); + collector.GetCapturedEntries().Should().ContainSingle().Which.Message.Should().Be("captured despite keyed provider"); + collector.Verify().AtLevelOrAbove(LogLevel.Error).InCategory("Keyed.Category").Once(); + } + private static IHost CreateHost(LogCollector collector) { var builder = Host.CreateApplicationBuilder(); @@ -139,4 +161,13 @@ private static IHost CreateHost(LogCollector collector) builder.Logging.AddComponoCapture(collector); return builder.Build(); } + + private sealed class NoOpLoggerProvider : ILoggerProvider + { + public ILogger CreateLogger(string categoryName) => NullLogger.Instance; + + public void Dispose() + { + } + } }