Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,27 @@
<ItemGroup Label="Microsoft.Extensions.Options (net11.0)" Condition="'$(TargetFramework)' == 'net11.0'">
<PackageVersion Include="Microsoft.Extensions.Options" Version="[11.0.0, 12.0.0)" />
</ItemGroup>
<!-- test/Compono.Logging.Tests' own dependencies - a real Generic Host and the concrete logging
implementation for #164's host-wide capture tests (B3/B4). Test-only: no src project references
these, and they never appear in Compono.Logging's shipped dependency graph (ADR-0071 keeps it
Abstractions-only). Each TFM gets its own release line, matching the Abstractions groups above;
exact versions, not ranges, because these are tests, not a shipped constraint. -->
<ItemGroup Label="Microsoft.Extensions.Hosting/Logging test-only (net8.0)" Condition="'$(TargetFramework)' == 'net8.0'">
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="8.0.1" />
</ItemGroup>
<ItemGroup Label="Microsoft.Extensions.Hosting/Logging test-only (net9.0)" Condition="'$(TargetFramework)' == 'net9.0'">
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="9.0.23" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="9.0.23" />
</ItemGroup>
<ItemGroup Label="Microsoft.Extensions.Hosting/Logging test-only (net10.0)" Condition="'$(TargetFramework)' == 'net10.0'">
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="10.0.15" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="10.0.15" />
</ItemGroup>
<ItemGroup Label="Microsoft.Extensions.Hosting/Logging test-only (net11.0)" Condition="'$(TargetFramework)' == 'net11.0'">
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="11.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="11.0.0" />
</ItemGroup>
<ItemGroup>
<!-- Assertions -->
<PackageVersion Include="AwesomeAssertions" Version="9.6.0" />
Expand Down
81 changes: 81 additions & 0 deletions docs/adr/0071-compono-logging-host-wide-log-capture.md
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,87 @@ 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.

### 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
Expand Down
9 changes: 7 additions & 2 deletions docs/documentation-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
│ └── <one page per narrow, practical problem — expected to grow into the
Expand Down Expand Up @@ -286,6 +287,8 @@ Decision Drivers named:
- `register-a-type.md` — how do I register a type?
- `use-profiles.md` — how do I use profiles?
- `share-a-value-across-a-test.md` — how do I share a value across a test?
- `assert-nothing-logged-at-error-across-a-host.md` — how do I assert
nothing logged at Error or above across a Generic Host?
**Relates to:** assumes Concepts. Hands off to Cookbook for narrower,
single-snippet variants of the same tasks, to Best Practices for "what's
the recommended way to do this at scale," and to Package Guides for
Expand Down Expand Up @@ -501,7 +504,9 @@ step in the linear reading order.
**Contents:**
- `common-errors.md` — indexed by diagnostic code (e.g. `CMP0001`, the
real gap Milestone 7's dogfooding surfaced) and by symptom ("why did
composition fail," "why is my substitute returning null").
composition fail," "why is my substitute returning null," "why does
`Verify()` throw on a host `ILogger<T>`," "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
Expand Down
184 changes: 184 additions & 0 deletions docs/how-to/assert-nothing-logged-at-error-across-a-host.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
# 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<T>` produced the entry. See
[`Compono.Logging`'s Package Guide](../packages/compono-logging.md#host-wide-capture-with-logcollector-and-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` 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
an exact, ordinal, case-sensitive comparison of the entry's `Category`:

```csharp
logs.Verify()
.AtLevelOrAbove(LogLevel.Error)
.InCategory("MyApp.Payments.PaymentGateway")
.Never();
```

For a host entry, `Category` is exactly the string the logging pipeline
passed to `ILoggerProvider.CreateLogger` — for an `ILogger<PaymentGateway>`,
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

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. 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

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<Program>
{
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.

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<ApiFactory>
{
[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 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

- [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<T>` rather than host-wide
capture.
1 change: 1 addition & 0 deletions docs/how-to/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading