Skip to content

Releases

v0.17.0

Choose a tag to compare

@github-actions github-actions released this 24 Nov 18:00
Immutable release. Only release title and notes can be modified.
v0.17.0
8ad54b1

[0.17.0] - 2026-11-24: log definitions generated from [LoggerMessage]

BREAKING

  • LogDefinition.Properties was removed: a definition is the identity of a log call, and the argument values of a capture moved to LogCall.Properties. Migration: capture with LogCall.Capture(...) and read call.Properties; for the placeholder names alone, read LogDefinition.PlaceholderNames.
  • LogDefinition.Exception was removed, for the same reason. Migration: LogCall.Capture(...), then call.Exception.
  • LogDefinition.Level changed from LogLevel to LogLevel?: a generated definition has no level when its method takes the level as a parameter. A captured definition still holds the level of the capture call. Migration: definition.Level ?? ..., or definition.Level!.Value where the definition is captured.
  • LogDefinition.Template is null for an empty template: an empty template is no template. LogDefinition.Capture of a [LoggerMessage] method without a message used to return "" (Microsoft.Extensions.Logging.Abstractions writes an empty template; Microsoft.Extensions.Telemetry writes none), and LogContractRenderer.Render and LogDefinition.ToString() wrote "" for it; it now returns null, and both write <no template>. Matching treats an empty template and none alike. Migration: regenerate a contract baseline that holds such a method, and review the diff.
  • LogFilter.MatchingCall takes a LogCall instead of a LogDefinition. A generated definition has no argument values, so passing one to the exact-call filter is a build error now, not a filter that never matches. The chain's MatchingCall(log => ...) is unchanged. Migration: LogFilter.MatchingCall(LogDefinition.Capture(...)) becomes LogFilter.MatchingCall(LogCall.Capture(...)).

Added

  • [assembly: GenerateLogDefinitions(typeof(T))]: a source generator, shipped in the LogAssertions package, writes a LogDefinition for each [LoggerMessage] method of the assembly that contains T, at compile time and without reflection. For each type it adds an internal class <Type>LogDefinitions in the type's namespace with one field per method, so a test writes HasLogged().Matching(OrderServiceLogDefinitions.LogOrderShipped) without a capture lambda or throwaway arguments. A generated definition carries the identity the method's records carry, whichever of Microsoft's two logging generators compiled the product (Microsoft.Extensions.Logging.Abstractions or Microsoft.Extensions.Telemetry): the attribute's event ID, or, when it sets none, the ID the product's logging generator derives, as each version derives it (a hash of the event name; -1 before Microsoft.Extensions.Logging.Abstractions 8.0; 0 before Microsoft.Extensions.Telemetry 8.2; a hash of the C# text for the name in Telemetry 8.2 to 9.7); the event name as the record carries it (a backslash escape in it takes effect, with either generator), or the method name when it is empty or whitespace; the template as the record carries it (with Microsoft.Extensions.Logging.Abstractions before 11.0 a backslash escape in the message takes effect); and the placeholder names in the record's order, including the parameters the template does not use (with Microsoft.Extensions.Telemetry, not a data-classified one). With Microsoft.Extensions.Telemetry, a [TagName], [TagProvider] or [LogProperties] parameter keeps its own name in PlaceholderNames (the first two are not compiled into the product, and the generator does not expand the properties of the third), and so, with Microsoft.Extensions.Logging.Abstractions 8.0 and later, does a parameter of a referenced assembly written with an @ its name does not need (a compiled assembly does not record it); matching is not affected. A project that references only LogAssertions.TUnit gets the generator too. The generator sees public and protected methods, and internal ones when the product names the test project in InternalsVisibleTo; a private method is not in the reference assembly a test project compiles against, and the generator applies the same rule to a project reference in an IDE, so the editor and the build agree.
  • GenerateLogDefinitionsAttribute (with TypeInAssembly): the assembly attribute that opts a product assembly in, named by any type in it; apply it once per product assembly.
  • Generator warnings LOGA001 to LOGA004, reported at the GenerateLogDefinitions attribute: an opted-in assembly has no [LoggerMessage] method the test project can see; two methods of a type share a name, so neither gets a definition; two types would generate the same class, so neither does; a generated name is taken (a type the test project sees, or a namespace, already has the class's full name, a type the test project sees has the full name of one of its namespaces, or a method is named like the class), so it is left out.
  • LogDefinition.Create(EventId, LogLevel?, string?): builds a definition from its parts, reading the placeholder names from the template, for a record whose logging code a test cannot call.
  • LogDefinition.Create(EventId, LogLevel?, string?, IEnumerable<string>): the same with the placeholder names as given. The generated definitions use it.
  • LogDefinition.PlaceholderNames: the names of the placeholder values a record of the definition carries.
  • LogCall: one captured log call, LogCall.Capture(log => ...), with its Definition, Properties, and Exception, for LogFilter.MatchingCall.

Changed

  • LogContractRenderer.Render writes ? as the level of a definition without one (a generated definition whose method takes the level as a parameter). Lines of captured definitions are unchanged.
  • README: a section on the generated definitions, and the recommendation to give each [LoggerMessage] method an explicit EventId, so a renamed method keeps its event ID.

v0.16.0

Choose a tag to compare

@github-actions github-actions released this 17 Nov 21:37
Immutable release. Only release title and notes can be modified.
v0.16.0
89c0aa2

[0.16.0] - 2026-11-17: the not-teed line names its records

Changed

  • The tee's "N log record(s) were not teed" line names the levels of the records it skipped, most severe first, and the first one's level and category: 3 log record(s) were not teed to a test report (1 Information, 2 Debug; the first: [Information] Shop.Orders): .... A reader can tell whether a lost record matters without a rerun.
  • WaitForLogAsync and WaitForLogsAsync documentation points to WillLog(timeout, cancellationToken) for a bounded wait that fails with the captured records.

v0.15.1

Choose a tag to compare

@github-actions github-actions released this 17 Nov 20:31
Immutable release. Only release title and notes can be modified.
v0.15.1
1b7f9b5

[0.15.1] - 2026-11-17: a record a test has seen is in its report

Fixed

  • AddTeedFakeLogging and TestOutputLogCollectorBuilder.CreateTeed(): a record that a test had seen could be missing from its report. The collector stored a record before the tee wrote it. A test that waited for a record logged on another flow could see it, pass and end while the tee was still formatting it, and the tee then skipped it as a record of an ended test. The tee now writes a record before the collector stores it.
  • AddTeedFakeLogging with a null collector registered the tee before it threw ArgumentNullException. It now checks both arguments first and leaves the builder unchanged.

v0.15.0

Choose a tag to compare

@github-actions github-actions released this 15 Nov 20:56
Immutable release. Only release title and notes can be modified.
v0.15.0
66e0de5

[0.15.0] - 2026-11-15: event ID allowlist, compact dumps with exceptions, .NET 11

BREAKING

  • LogCapture.Deconstruct was removed, as 0.14.0 announced. It only turned var (factory, collector) = LogCollectorBuilder.Create(); into a build error that named the new form; that line now fails with the compiler's own error (CS1061, no Deconstruct on LogCapture). Source that compiled against 0.14.x never contained the call, so this changes binary compatibility only. Migration: using var logs = LogCollectorBuilder.Create();, then logs.Collector (await using var in async code).
  • LogContractRenderer.Render output changed in two cases. Definitions that tie on event ID, name, template, and level used to keep their input order, so the same set could render in two orders; they are now ordered by their rendered line as well. The event name and the placeholder names are now escaped like the template (\\, \", CR, LF, and tab), so a name with a line break no longer splits its line. A committed contract baseline changes only if it held such a tie or such a name. Migration: regenerate the baseline and review the diff.

Added

  • Targets net10.0 and net11.0. Each target framework resolves its own Microsoft.Extensions.Diagnostics.Testing (10.11.0 for net10.0, 11.0.0 for net11.0).
  • WithEventIdIn(params int[] eventIds) on every assertion chain (HasLogged, HasNotLogged, HasLoggedSequence steps, WillLog) and LogFilter.WithEventIdIn(params int[] eventIds): records whose event ID is any of the listed IDs, in place of LogFilter.Any(LogFilter.WithEventId(a), LogFilter.WithEventId(b)). Duplicates count once. An empty list throws ArgumentException, because a filter that accepts nothing is almost always a mistake and would make HasNotLogged() pass for no reason. The failure text names the call with its distinct IDs and describes the filter as EventId in {1, 2}, with braces, so it is not taken for the range of WithEventIdInRange.
  • DumpVerbosity.CompactWithException (value 3, appended after Verbose; the values of the other members did not change): the Compact headline of each record plus one exception: Type: message line for a record that carries an exception, with no properties and no scopes. It works with DumpTo, DumpToTestOutput, and both DumpToTestOutputOnFailure overloads; a dump of 46 records, three of them with an exception, is 49 lines.

Changed

  • TUnit.Assertions and TUnit.Core minimum versions raised from 1.81.10 to 1.85.0: 1.83.0 is the first TUnit with a net11.0 asset, and 1.85.0 keeps TUnit's OpenTelemetry and ASP.NET Core packages on OpenTelemetry 1.20.x for net10.0, so a project with one version for all its TUnit packages gets no .NET 11 packages there.
  • README: the shared-host recipe (build and start a host that outlives a test inside Task.Run within ExecutionContext.SuppressFlow() and await it after the block, because suppressing the flow does not clear the calling thread's own context) is in the TUnit adapter README and in the remarks of AddTeedFakeLogging as well; the lifetime attribute is needed once in every test assembly, also when the package arrives through another project; a new cookbook entry, "Pin the records other tools read", shows WithEventName(...).WithMessageTemplate(...) for a record the contract renderer cannot reach; the troubleshooting entry for the removed Deconstruct names the new error; every C# sample compiles against the packed packages.

Fixed

  • Dumps and failure messages (DumpTo, DumpToTestOutput, DumpToTestOutputOnFailure, and the captured records in an assertion failure) wrote an exception message with line breaks as several lines, the later ones without indentation. The exception: line now shows the message on one line, each line break replaced by a space; Verbose still writes the full exception text below it.
  • Captured records in failure messages and dumps wrote a captured message, category, property key or value, or scope text that held a line break as several lines, the later ones without indentation, so they could be mistaken for records or detail lines of their own. Each now stays on one line, each line break replaced by a space, as the exception message does. LogSnapshotRenderer is unchanged: it writes the captured text verbatim, as documented.
  • Filter descriptions and the allowlist (the matching: and Step filters: clauses of a failure, the filter named by a canceled wait, and the Allowed definitions: lines of HasLoggedOnly) wrote a substring, key, template, or event name that held a line break as several lines. Each line break is now one space.
  • Expression text of a failure (.Containing(...), .WithProperty(...), .WithCategory(...), and the other chain methods that take a string, a value, or a definition) wrote the caller's argument raw, so a line break in it split the expression line and a quote or backslash made it ambiguous. The text now reads as a C# string literal does: \, ", CR, and LF are written as \\, \", \r, and \n, and the other line breaks the failure text recognizes (form feed, NEL, LS, and PS) as \f, \u0085, \u2028, and \u2029.
  • HasNotLogged() failure showed only the last 50 captured records, so a matching record older than that was not in the message. When an older match would be hidden, the message now lists the matching records themselves (Matching records (N of M captured):, capped at the latest 50 after a line that counts the earlier ones). When the last 50 captured records hold every match, the message is unchanged.

v0.14.1

Choose a tag to compare

@github-actions github-actions released this 09 Nov 18:56
Immutable release. Only release title and notes can be modified.
v0.14.1
e34042f

[0.14.1] - 2026-11-09: tee, failure dump, and waits fixed at their edges

Patch release, no API change. The test-output tee keeps each record with its exception text and never writes into a test that ended while the record was being formatted; a dump armed or a tee built before TUnit starts the test no longer claims the lifetime attribute is missing; a failure dump ends with its summary; a wait whose token or timeout ends it returns the matching records the collector already holds.

Changed

  • TUnit.Assertions and TUnit.Core minimum versions raised from 1.80.0 to 1.81.10.
  • README: a record logged in a test class's DisposeAsync is not teed, since TUnit disposes the class after the test has ended (log in the test or an [After(Test)] hook); a retried test keeps one output across its attempts; a capture shared by tests that run at the same time puts each test's records in the others' dumps; the dump section describes how much of a test's output TUnit keeps.

Fixed

  • The built-in test-output tee (CreateTeed, CreateTeedDiscarding, AddTeedFakeLogging) wrote a record into a test that ended while the record was being formatted, and did not count it. A record that races the end of its test is now skipped and counted, never written into the ended test.
  • The built-in test-output tee wrote a record and its exception text as two writes, so a record logged on another thread at the same moment could land between them and the stack trace showed under the wrong record. Each record is now written together with its exception text.
  • DumpToTestOutputOnFailure() in a [Before(Class)] hook, a test class's constructor, or a fixture's initialization threw "needs the LogAssertionsTestLifetime attribute" in a project that applies it, because TUnit runs these before it starts the test. It now throws a message that says the call came before TUnit started the test. A tee built there no longer writes the "this test project does not apply the LogAssertionsTestLifetime attribute" note into the report.
  • DumpToTestOutputOnFailure(): TUnit keeps only the last ~786,000 characters of a test's output, so the report of a very large dump lost its heading. The dump now ends with a line that repeats the summary (End of dump: 3 of 120 records.), and every record is still written.
  • WillLog(...) failed when its timeout fired just after the matching record was captured, or when its token was already canceled while the matching records were there, with a contradictory message such as "the wait was canceled with 1 record(s) matched" under Once(). The records the collector holds when the wait ends now decide.
  • FakeLogCollector.WaitForLogAsync and WaitForLogsAsync threw OperationCanceledException when the token was canceled while the collector already held the matching records, and the message counted none. They now return those records, and the message of a canceled wait counts the records the collector holds and the matching ones among them. To decide, a canceled wait runs the filter again over the collector's records, so a filter may run more than once for the same record; the README and the ILogRecordFilter docs now say so (keep custom filters free of side effects).

v0.14.0

Choose a tag to compare

@github-actions github-actions released this 06 Nov 19:41
Immutable release. Only release title and notes can be modified.
v0.14.0
5241209

[0.14.0] - 2026-11-06: one log capture, a wait with diagnostics, failure dumps, and a tee that respects the test's lifetime

Minor release with breaking changes. LogCollectorBuilder.Create() returns a LogCapture; WillLog(...) waits for background work and fails with the standard diagnostics; an opt-in assembly attribute lets the package see each test's end, which enables a dump of the captured records when a test does not pass and keeps the test-output tee out of finished tests. Also: a rate-limit terminator, a log contract renderer, a teed factory that keeps nothing, and a fix for records with custom state.

BREAKING

  • LogCollectorBuilder.Create(LogLevel) and TestOutputLogCollectorBuilder.CreateTeed(LogLevel) return a LogCapture instead of a (Factory, Collector) tuple, so var (factory, collector) = LogCollectorBuilder.Create(); and .Factory member access no longer compile (.Collector still does), and code compiled against 0.13 must be recompiled. The deconstruction fails with a build error that names the new form. Migration: using var logs = LogCollectorBuilder.Create();, then use logs as the ILoggerFactory and logs.Collector for assertions. LogCapture is also IAsyncDisposable, so in async code write await using var logs = ...; analyzers such as Roslynator RCS1261 and Meziantou MA0042 report a plain using or an explicit Dispose() call there.
  • FakeLoggingBuilderExtensions.AddTeedFakeLogging lost its ILoggerProvider? teeProvider parameter, including calls that pass it by name. Passing a new provider there raised CA2000 at every call site, and the logging factory never disposed it. Migration: chain the provider, .AddTeedFakeLogging(collector, level).AddProvider(provider); for TUnit's correlated console output, .AddFakeLogging(collector, level).AddCorrelatedTUnit(level) from TUnit.Logging.Microsoft.
  • HasLogged() counts that admit zero (Never(), AtMost(n), Exactly(0), Between(0, n), and the HasLoggedAtMost(n) / HasLoggedExactly(0) / HasLoggedBetween(0, n) shorthands) fail as vacuous when every level the chain targets sits below the collector's capture floor, as HasNotLogged() already did. Such an assertion used to pass because nothing at those levels was captured. Migration: assert at a captured level, or lower the floor (LogCollectorBuilder.Create(minimumLevel)).
  • The built-in test-output tee (CreateTeed, AddTeedFakeLogging) no longer writes a record that no running test claims into a test that has ended; the record is skipped and counted (see Changed). This changes test output only, not assertion outcomes.

Added

  • LogCapture (core): the logger factory and its FakeLogCollector in one disposable object. It implements ILoggerFactory (pass it wherever a factory is expected) and IAsyncDisposable; disposing it disposes the factory and its providers, including one added with AddProvider, and the collector keeps its records. Disposal does not stop capture: a logger created before keeps writing into the collector.
    • Its Deconstruct exists only to turn the 0.13 tuple form into a build error that names the new form; it is hidden from IntelliSense, cannot be called, and is removed in a later minor version.
  • LogCollectorBuilder.Create(TimeProvider timeProvider, LogLevel minimumLevel = LogLevel.Trace) and TestOutputLogCollectorBuilder.CreateTeed(TimeProvider timeProvider, LogLevel minimumLevel = LogLevel.Trace): the collector stamps each record with timeProvider's time, so AtMostOncePer and the times in a failure dump follow a fake clock. Without a clock, timestamps come from the system clock, as before. A project that runs Meziantou MA0166 / MA0167 now gets a diagnostic at each call without a clock: pass the fake clock in scope, else TimeProvider.System.
  • [assembly: LogAssertions.TUnit.LogAssertionsTestLifetime]: an opt-in attribute, applied once per test project, that receives TUnit's start (before the [Before(Test)] hooks) and end (after the [After(Test)] hooks) of every test, once per attempt of a retried test. TUnit offers no public way for code inside a test to observe its end. The attribute enables DumpToTestOutputOnFailure() and makes the tee's routing exact. All its state is static and keyed weakly by the test's TestContext. Without it, the first built-in tee built in a test run writes one note to that test's output, naming the line to add.
  • Assert.That(collector).WillLog(TimeSpan timeout, CancellationToken cancellationToken = default) (WillLogAssertion): the event-driven form of HasLogged(), built on WaitForLogsAsync.
    • It waits on the collector's stream of records, with no polling and no real-time delay. The count is read from the collector right after the minimum number of matching records has been captured; records captured by then count, including ones logged before the assertion ran, and a record that arrives after the assertion has passed isn't checked.
    • It fails when that count exceeds the maximum, and at once when the chain's levels all sit below the capture floor.
    • When the timeout or the token ends the wait, it fails with the expectation, the count, and the captured records, not a bare cancellation. The timeout is required and real time, whatever the collector's clock, and starts when the assertion runs, not when the chain is built.
    • Terminators: Once(), Exactly(n), AtLeast(n), Between(min, max) with counts of at least 1, plus GetMatch() and GetMatches(), which run the assertion; inside Assert.Multiple(), after a failed wait they throw InvalidOperationException naming the failure. There is no Never() or AtMost(n), since a wait cannot prove absence.
  • HasLogged()...AtMostOncePer(TimeSpan interval): every gap between consecutive matching records, ordered by FakeLogRecord.Timestamp (the collector's clock), must be at least interval: two records exactly interval apart pass, one tick less fails. The failure names the first pair that was too close, with timestamps, the gap, and the number of short gaps. It constrains spacing only: HasLogged() still needs at least one match unless a count that admits zero is set, in either order.
  • FakeLogCollector.DumpToTestOutputOnFailure() and DumpToTestOutputOnFailure(DumpVerbosity), called in a test or a [Before(Test)] hook (needs the lifetime attribute):
    • When the test ends without passing (failed, timed out, or canceled; not skipped), every record captured since the call is written to its output, with its timestamp (UTC, from the collector's clock). A test that passes writes nothing.
    • The start point is the collector's latest record at the call, not a clock reading, so it is right with a fake clock; if the collector is cleared, every record is written.
    • A retried test arms again in each attempt, and the heading names the attempt.
    • Without the attribute it throws InvalidOperationException with the line to add.
  • TestOutputLogCollectorBuilder.CreateTeedDiscarding(LogLevel minimumLevel = LogLevel.Trace): an enabled ILoggerFactory that keeps no records and tees every record to the test report, for fixtures and long-lived hosts whose logs nobody asserts on.
  • LogContractRenderer.Render(IEnumerable<LogDefinition>) (core, LogAssertions.Render): one deterministic line per definition, for example 1201 OrderProcessed Information "Order {OrderId} processed in {DurationMs} ms" OrderId,DurationMs.
    • Placeholder names are in template order. Lines are ordered by event ID, then name, template, and level, and end in LF, with no header.
    • Templates are escaped to stay on one line.
    • Composed with MatchesSnapshot(), the log contract becomes a reviewed baseline.

Changed

  • The built-in test-output tee picks the test for each record when it is logged:
    • the test current at the log call;
    • otherwise the test current when the tee was built, while that test runs;
    • otherwise no test.
      With the lifetime attribute a test counts as running until its [After(Test)] hooks finish, and a record on the flow of a test that has ended is not teed either. Without the attribute the fallback ends when the owning test has a result. Records that reach no test are counted, and disposing the factory writes the count to the test current then. The tee is now registered so that the logging container disposes it.
  • Failure messages of every assertion (HasLogged(), HasNotLogged(), HasLoggedSequence(), HasLoggedOnly(), WillLog()) show the last 50 captured records, after one line (N earlier record(s) not shown) when there are more. A long run's collector can hold thousands of records. The explicit dumps (DumpTo, DumpToTestOutput, DumpToTestOutputOnFailure) still write every record.
  • TUnit.Assertions and TUnit.Core minimum versions raised from 1.77.0 to 1.80.0.
  • README and XML docs (all three READMEs):
    • Setup and upgrade: a Setup section for the lifetime attribute and an upgrade table for 0.14.0.
    • Background work: uses WillLog instead of polling with Eventually, with a recipe for background work on a fake clock (start the assertion, advance the clock, then await it).
    • Clocks: each member that reads time says which clock: record timestamps come from the collector's clock, and WillLog's timeout is real time.
    • Shared hosts: a table of where each record goes. A background loop keeps the context of the test that started it, so build and start a shared host inside ExecutionContext.SuppressFlow(): TUnit runs hooks such as [Before(Class)] and shared-fixture initialization on the flow of the first test that needs them.
    • Private [LoggerMessage] methods: matched by WithEventId / WithEventName, without making them internal.
    • Corrected claims:
      • disposing the factory does not stop capture;
      • AssertAllAsync needs `using LogAssertions.T...
Read more

v0.13.1

Choose a tag to compare

@github-actions github-actions released this 02 Nov 18:21
Immutable release. Only release title and notes can be modified.
v0.13.1
b73e7cf

[0.13.1] - 2026-11-02: discarding loggers return a scope

Patch release. LogCollectorBuilder.CreateDiscarding loggers now return a scope from BeginScope, as NullLogger and the other common loggers do.

Fixed

  • LogCollectorBuilder.CreateDiscarding loggers returned null from BeginScope. The ILogger contract allows that, but NullLogger and the common production loggers return a scope, so code that requires a scope instance passed in production and threw under a discarding logger. BeginScope now returns a shared scope whose disposal does nothing.

v0.13.0

Choose a tag to compare

@github-actions github-actions released this 01 Nov 12:40
Immutable release. Only release title and notes can be modified.
v0.13.0
bb297fa

[0.13.0] - 2026-11-01: wait for a log from background work, a discarding logger factory

Minor release. Event-driven waits return once background work has logged a matching record, without polling; LogCollectorBuilder.CreateDiscarding gives an enabled logger that keeps nothing; the sequence and When configurators take expression lambdas. One source-breaking edge (see Changed).

Added

  • FakeLogCollector.WaitForLogAsync(ILogRecordFilter filter, CancellationToken cancellationToken) waits until the collector holds a record that matches the filter and returns it. It is built on FakeLogCollector.GetLogsAsync, so it wakes on each new record, with no polling interval and no real-time delay; records logged before the call count. On cancellation the OperationCanceledException says how many records arrived and how many matched.
  • FakeLogCollector.WaitForLogAsync(Func<FakeLogRecord, bool> predicate, CancellationToken cancellationToken) is the predicate form.
  • FakeLogCollector.WaitForLogsAsync(ILogRecordFilter filter, int count, CancellationToken cancellationToken) waits for count matching records and returns them in the order they were logged.
  • LogCollectorBuilder.CreateDiscarding(LogLevel minimumLevel = LogLevel.Trace) returns an ILoggerFactory whose loggers are enabled at minimumLevel and above but keep nothing, so code guarded by logger.IsEnabled(...) runs its logging branch under coverage without a collector that grows in a long-lived host. It replaces the discarding provider the README used to show.
  • HasLoggedSequence().ThenAnyOrder(params Func<HasLoggedSequenceAssertion, HasLoggedSequenceAssertion>[]) and When(bool, Func<TSelf, TSelf>) (on every HasLogged / HasNotLogged / HasLoggedSequence chain) take configurators that return the assertion, which is what an expression lambda such as s => s.Containing("x", StringComparison.Ordinal) does. Such lambdas now bind to these overloads, so the awaitable assertion they return is observed instead of discarded, and analyzers that require awaitables to be observed (Meziantou.Analyzer MA0134 from 3.0.318, Microsoft.VisualStudio.Threading.Analyzers VSTHRD110 from 18.12) no longer report every configurator. Statement-lambda configurators keep binding to the existing Action overloads, with the same semantics. A ThenAnyOrder call that mixes a statement lambda with expression lambdas binds as a whole to the Action overload, so its expression lambdas still discard their result; write every sub-step of such a call as an expression lambda.

Changed

  • BREAKING: ThenAnyOrder() with no argument no longer compiles; pass Array.Empty<Action<HasLoggedSequenceAssertion>>() instead. ThenAnyOrder(null) and When(condition, null) with a bare null need a cast to the Action or Func type to choose an overload. Calls that pass lambdas are unaffected.
  • TUnit.Assertions and TUnit.Core minimum versions raised from 1.58.0 to 1.77.0, and Microsoft.Extensions.Diagnostics.Testing from 10.7.0 to 10.11.0 (GetLogsAsync, which the waits build on, needs 10.9.0 or later).
  • README: waiting for a log from background work uses WaitForLogAsync instead of polling with Eventually; the HasLoggedOnly section frames the gate as an audit that is expected to fail the first time and points to counts; the snapshot section recommends a scrubber set and explains migrating from a hand-rolled renderer; TUnit.Mocks.Logging is compared with collector capture.

v0.12.0

Choose a tag to compare

@github-actions github-actions released this 11 Jul 17:33
v0.12.0
3ba5ec1

[0.12.0] - 2026-07-11: gate a run on its log output

Minor release. Adds the assertion the rest of the DSL was missing: HasLogged() and friends assert that an expected record is present, while the new gate asserts that no unexpected one is. Additive; no existing API changed.

Added

  • Assert.That(collector).HasLoggedOnly(floor).Allowing(definitions) asserts that every captured record at or above floor carries the identity of an allowed [LoggerMessage] definition. Records below the floor are always permitted and are never enumerated, which is what makes the gate usable on a service whose Debug and Trace volume (heartbeats, request bodies) is large while its warning-and-above band is small enough to list. With no Allowing(...) call the gate is the clean-run check: nothing was logged at or above the floor at all. Because it keys on definition identity rather than rendered text, a reworded template cannot slip an unexpected record past it. Assert it once per test class or fixture (a TUnit [After] hook over the fixture's collector) rather than per test. When the collector's capture floor sits above the gate's floor the records it claims to inspect were never captured, so the gate fails as vacuous rather than passing for the wrong reason, matching the guard HasNotLogged() already had.
  • MatchingAny(LogDefinition, params LogDefinition[]) on the assertion chains, and LogFilter.MatchingAny(LogDefinition, params LogDefinition[]) in the framework-agnostic core, filter to records carrying the identity of any of the given definitions. This covers one logical event that is emitted by more than one definition, such as a verbose form that attaches the exception and a terse form that folds the exception text into the message, selected at run time by a flag. There is deliberately no conjunction counterpart: a record carries exactly one identity, so requiring it to match two distinct definitions could never be satisfied.
  • Step(LogDefinition) on HasLoggedSequence() adds a strictly-ordered typed step, so a flow reads as one call per event (.Step(OrderReceived).Step(PaymentCaptured).Step(OrderShipped)) instead of alternating Matching(...) and Then(). Further filters chain onto the step just opened.

Changed

  • Documented where [LoggerMessage] definitions must live to be assertable: internal (with [InternalsVisibleTo]) or public, and not on a generic type. Roslynator's RCS1158 ignores private members, so a private definition on a generic base compiles until it is promoted to internal for typed capture, at which point the build breaks; hosting definitions in a non-generic static partial class resolves it and reads better at the capture site. Also documented that negative assertions gain the most from typed definitions (a substring HasNotLogged() silently passes once the wording drifts; an identity-keyed one cannot), and when to reach for a rendered LogSnapshotRenderer snapshot instead.

v0.11.0

Choose a tag to compare

@github-actions github-actions released this 11 Jul 10:40
v0.11.0
747acf7

[0.11.0] - 2026-07-11: typed assertions against log definitions

Minor release. A [LoggerMessage] definition (or any other log call) becomes a reusable assertion value: capture it once, then assert it was logged by identity instead of matching rendered message text. Wording edits to a template no longer break tests that assert intent; renaming a definition or changing its signature breaks the capture lambda at compile time. Binary-compatible and additive; one source-level compatibility note is listed under Changed. Built against TUnit 1.58; pin TUnit at or above that version when adopting.

Added

  • LogDefinition.Capture(Action<ILogger>) (core) invoked a logging delegate once against a private probe logger and returned the captured call shape: event ID (numeric ID plus name), level, message template, formatted placeholder values, and exception. The probe collects every level, so an IsEnabled gate inside generated logging code cannot suppress the capture. A lambda that logs zero or multiple records fails fast with an explanatory ArgumentException. Argument values in the capture lambda are throwaway; store definitions in static readonly fields.
  • Matching(LogDefinition) on the HasLogged() / HasNotLogged() / HasLoggedSequence() chains filtered to records carrying the definition's identity: equal event ID, event name, and message template. Argument values and level are deliberately not part of identity: chain WithProperty(...) to pin placeholder values and AtLevel(...) when the level matters. Works for definitions behind wrapper methods (the record carries the generated Core's identity), definitions with generator-assigned event IDs, and definitions hosted in generic classes (close the generic in the capture lambda).
  • MatchingCall(Action<ILogger>) on the same chains matched a log call exactly: the definition's identity plus every placeholder value (formatted strings, order-insensitive, culture-invariant) plus the exception (both absent, or same runtime type and equal message). The lambda is invoked once against the probe at chain-build time with the exact argument values expected.
  • LogFilter.Matching(LogDefinition) and LogFilter.MatchingCall(LogDefinition) exposed the same matching as composable ILogRecordFilter factories for reuse via WithFilter(...) and LogFilter.All / Any / Not.

Changed

  • LogFilter.Matching(null!) call sites became ambiguous between the Regex and LogDefinition overloads; a null-literal argument needs a cast to pick one. Compiled code is unaffected.