Skip to content

Add Microsoft.Testing.Extensions.Logging bridge to Microsoft.Extensions.Logging - #8344

Merged
Amaury Levé (Evangelink) merged 2 commits into
mainfrom
dev/amauryleve/mel-logging-bridge
May 19, 2026
Merged

Amaury Levé (Evangelink) merged 2 commits into
mainfrom
dev/amauryleve/mel-logging-bridge

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Adds a new opt-in side-package, Microsoft.Testing.Extensions.Logging, that lets users forward Microsoft.Testing.Platform's diagnostic log messages to any Microsoft.Extensions.Logging provider — Console, Debug, Serilog, OpenTelemetry, Application Insights, custom sinks, and so on. MTP's homegrown Microsoft.Testing.Platform.Logging stays in core (zero dependencies, AOT-friendly, netstandard2.0); the bridge is purely additive and is never referenced by core or by any existing extension.

This is phase 1 of the policy laid out in the new RFC 013 — Microsoft.Extensions.* Bridges. Future phases (Configuration, DI, Hosting) will follow the same shape.

Public API ([TPEXP])

namespace Microsoft.Testing.Extensions;

[Experimental("TPEXP", UrlFormat = "https://aka.ms/testingplatform/diagnostics#{0}")]
public static class MicrosoftExtensionsLoggingBuilderExtensions
{
    public static ITestApplicationBuilder AddMicrosoftExtensionsLogging(
        this ITestApplicationBuilder builder,
        Action<Microsoft.Extensions.Logging.ILoggingBuilder> configure);

    public static ITestApplicationBuilder AddMicrosoftExtensionsLogging(
        this ITestApplicationBuilder builder,
        Microsoft.Extensions.Logging.ILoggerFactory loggerFactory);
}

The first overload owns and disposes the MEL LoggerFactory; the second forwards to a caller-owned factory. Both short-circuit to a no-op when MTP's effective LogLevel is None (no --diagnostic), so expensive sinks (Application Insights connection setup, Serilog file sinks, OTLP exporters, …) are not constructed for runs that will never emit a log.

Usage:

ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args);
builder.AddMSTest(() => [Assembly.GetEntryAssembly()!]);

builder.AddMicrosoftExtensionsLogging(logging =>
{
    logging.AddConsole();
    // logging.AddSerilog(...);
    // logging.AddApplicationInsights(...);
});

using ITestApplication app = await builder.BuildAsync();
return await app.RunAsync();

Semantic mapping

MTP concept Mapped MEL concept Notes
LogLevel.Trace…Critical/None (0..6) Microsoft.Extensions.Logging.LogLevel Same numeric values; mapped via explicit switch for safety/AOT
Log<TState>(level, state, ex, formatter) Log<TState>(level, EventId.None, state, ex, formatter) EventId defaults to None
LogAsync<TState>(...) Synchronous Log + Task.CompletedTask MEL has no async API
IsEnabled(level) Forwards to MEL Per-category filters can only narrow, never widen
Disposal LoggerFactory.Dispose/DisposeAsync Owned factories disposed; caller-owned ones are not

Tightly coupled platform fix

Discovered via the rubber-duck and expert-reviewer passes: MTP's LoggerFactory was never disposed during host shutdown, so user-registered MEL providers like Serilog / Application Insights / OpenTelemetry would silently lose their final flush. The fix:

  • LoggerFactoryProxy now implements IDisposable (+ IAsyncDisposable on NETCOREAPP), forwarding to the wrapped factory with thread-safe idempotency (Interlocked.Exchange on _disposed). CreateLogger after Dispose throws ObjectDisposedException instead of silently dispatching.
  • CommonHost.RunAsync's finally block now disposes the proxy explicitly, after the explicit FileLoggerProvider disposal, so user-registered logger providers flush last. The proxy is skipped by the standard DisposeServiceProviderAsync loop (same pattern as FileLoggerProvider) so ordering is preserved.
  • LoggerFactory.Dispose got a // NOTE: comment flagging that, post-PR, this method is now reachable at runtime so future authors notice when adding new shared ILoggerProvider registrations.

Tests (all passing)

  • 6 acceptance tests (MicrosoftExtensionsLoggingTests, 2 × 3 TFMs): forwarding works, short-circuit works (asserts the configure delegate is not invoked when --diagnostic is off), and the bridge-owned LoggerFactory is disposed at end of process so buffered MEL providers flush.
  • 6 new unit tests for LoggerFactoryProxy's disposal surface: idempotency, ObjectDisposedException post-dispose, IAsyncDisposable preference. 25/25 pass on net8/net9/net462.
  • 8 new unit tests for LogLevelMapper: exhaustive DataRow over all 7 levels + a future-proofing Enum.GetValues test that catches silent fallback to None if a new MTP LogLevel is ever added without updating the mapper. 32/32 pass on net8/net9/net462/net472.
  • No regressions: 36 DiagnosticTests still green (FileLoggerProvider lifecycle preserved).

Review

  • Rubber-duck review identified the missing LoggerFactory disposal before any code was committed, driving the platform-side fix.
  • 3 rounds of expert-reviewer (21 dimensions): all major and minor findings addressed.
  • Build.cmd -pack succeeds with 0 warnings, 0 errors. All 23 NuGet packages produced and content-validated, including the new Microsoft.Testing.Extensions.Logging.1.0.0-dev.nupkg.

Intentional non-goals (deferred to future phases)

  • Direction B (MTP ILoggerFactory exposed as Microsoft.Extensions.Logging.ILoggerFactory) — omitted from v1 to avoid speculative public API.
  • No new CLI options. Configuration is purely programmatic.
  • Does not replace the built-in --diagnostic file logger; both run together when --diagnostic is enabled.
  • No MSBuild auto-registration hook — the user must opt in with configure, so the TestingPlatformBuilderHook pattern does not apply.

Files

New:

  • docs/RFCs/013-Microsoft-Extensions-Bridges.md
  • src/Platform/Microsoft.Testing.Extensions.Logging/ (csproj, BannedSymbols, PACKAGE.md, PublicAPI, 4 internal classes + 2 public extension methods)
  • test/IntegrationTests/Microsoft.Testing.Platform.Acceptance.IntegrationTests/MicrosoftExtensionsLoggingTests.cs
  • test/UnitTests/Microsoft.Testing.Extensions.UnitTests/LogLevelMapperTests.cs

Modified:

  • Directory.Packages.props — added Microsoft.Extensions.Logging + Microsoft.Extensions.Logging.Console (the latter only consumed by samples/Playground).
  • TestFx.slnx, Microsoft.Testing.Platform.slnf — registered the new project.
  • samples/Playground/* — opt-in example wiring the bridge with AddSimpleConsole.
  • src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactoryProxy.cs — disposable + thread-safe idempotency.
  • src/Platform/Microsoft.Testing.Platform/Logging/LoggerFactory.cs — documentation note flagging new reachability.
  • src/Platform/Microsoft.Testing.Platform/Hosts/CommonTestHost.cs — explicit proxy disposal.
  • test/IntegrationTests/.../Helpers/AcceptanceTestBase.cs — extracts the new extension's alpha version.
  • test/UnitTests/.../LoggerFactoryProxyTests.cs — +4 tests covering new disposal surface.
  • test/UnitTests/Microsoft.Testing.Extensions.UnitTests/Microsoft.Testing.Extensions.UnitTests.csproj — references the bridge for unit testing.

…ns.Logging

A new opt-in side-package that lets users forward Microsoft.Testing.Platform's
diagnostic log messages to any Microsoft.Extensions.Logging provider (Console,
Debug, Serilog, OpenTelemetry, Application Insights, ...). MTP's homegrown
logging stays in core (zero deps, AOT-friendly, netstandard2.0); the bridge is
purely additive and never referenced by core or by existing extensions.

RFC 013 (`docs/RFCs/013-Microsoft-Extensions-Bridges.md`) codifies the policy
and outlines future phases (Configuration, DI, Hosting).

Public API (`[TPEXP]`):

  ITestApplicationBuilder.AddMicrosoftExtensionsLogging(Action<ILoggingBuilder>)
  ITestApplicationBuilder.AddMicrosoftExtensionsLogging(ILoggerFactory)

The first overload owns its MEL `LoggerFactory`; the second forwards to a
caller-owned factory. Both short-circuit to a no-op when MTP's effective
`LogLevel` is `None` (no `--diagnostic`), so expensive sinks are not
constructed for runs that will never emit a log.

Tightly coupled platform fix included: MTP's `LoggerFactory` was never
disposed at host shutdown, so buffered MEL providers (Serilog, App Insights,
OpenTelemetry) would silently lose their final flush. `LoggerFactoryProxy`
now implements `IDisposable`/`IAsyncDisposable` and is disposed explicitly
at the end of `CommonHost.RunAsync`'s finally block, after the explicit
`FileLoggerProvider` disposal, so user-registered logger providers flush
last.

Tests added:
  - 6 acceptance tests (2 x 3 TFMs) verifying forwarding, short-circuit, and
    end-of-process flush.
  - 4 unit tests for `LoggerFactoryProxy`'s new disposal surface
    (idempotency, `ObjectDisposedException` on post-dispose `CreateLogger`).
  - 8 unit tests for `LogLevelMapper` (exhaustive `DataRow` + future-proofing
    test).

Reviewed across three expert-review rounds: 21/21 dimensions clean.
`Build.cmd -pack` succeeds with 0 warnings, 0 errors.

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings May 19, 2026 07:27

@Evangelink Amaury Levé (Evangelink) left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of PR #8344 — Microsoft.Testing.Extensions.Logging bridge

# Dimension Verdict
1 Algorithmic Correctness ✅ LGTM
2 Threading & Concurrency ✅ LGTM
3 Security & IPC ✅ N/A
4 Public API & Binary Compat ✅ LGTM
5 Performance & Allocations ✅ LGTM
6 Cross-TFM Compatibility ✅ LGTM
7 Resource & IDisposable 🟡 1 NIT (see inline)
8 Defensive Coding ✅ LGTM
9 Localization ✅ LGTM
10 Test Isolation ✅ LGTM
11 Assertion Quality ✅ LGTM
12 Flakiness Patterns ✅ LGTM
13 Test Completeness ✅ LGTM
14 Data-Driven Coverage ✅ LGTM
15 Code Style ✅ LGTM
16 Naming & Conventions ✅ LGTM
17 Documentation ✅ LGTM
18 Analyzer Quality ✅ N/A
19 IPC Wire Compatibility ✅ N/A
20 Build Infrastructure ✅ LGTM
21 Scope & PR Discipline ✅ LGTM

✅ 20/21 dimensions clean.

  • NIT (MicrosoftExtensionsLoggingProvider.cs line 33): CreateLogger does not guard against post-dispose calls, unlike the symmetrical LoggerFactoryProxy.CreateLogger. See inline comment. Not blocking — unreachable in the current host shutdown ordering — but worth closing for consistency.

Generated by Expert Code Review (on open) for issue #8344 · ● 9.2M

- Guard MicrosoftExtensionsLoggingProvider.CreateLogger against post-dispose calls (mirrors LoggerFactoryProxy.CreateLogger).
- Register Microsoft.Testing.Extensions.Logging in NonWindowsTests.slnf so the package is produced on Linux/macOS CI and the acceptance-test ExtractVersionFromPackage lookup succeeds.

Co-authored-by: Copilot <[email protected]>
@Evangelink
Amaury Levé (Evangelink) merged commit 13b9a10 into main May 19, 2026
28 of 31 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/mel-logging-bridge branch May 19, 2026 14:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants