Repository navigation
Releases
v0.17.0
[0.17.0] - 2026-11-24: log definitions generated from [LoggerMessage]
BREAKING
LogDefinition.Propertieswas removed: a definition is the identity of a log call, and the argument values of a capture moved toLogCall.Properties. Migration: capture withLogCall.Capture(...)and readcall.Properties; for the placeholder names alone, readLogDefinition.PlaceholderNames.LogDefinition.Exceptionwas removed, for the same reason. Migration:LogCall.Capture(...), thencall.Exception.LogDefinition.Levelchanged fromLogLeveltoLogLevel?: 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 ?? ..., ordefinition.Level!.Valuewhere the definition is captured.LogDefinition.Templateisnullfor an empty template: an empty template is no template.LogDefinition.Captureof a[LoggerMessage]method without a message used to return""(Microsoft.Extensions.Logging.Abstractions writes an empty template; Microsoft.Extensions.Telemetry writes none), andLogContractRenderer.RenderandLogDefinition.ToString()wrote""for it; it now returnsnull, and both write<no template>.Matchingtreats an empty template and none alike. Migration: regenerate a contract baseline that holds such a method, and review the diff.LogFilter.MatchingCalltakes aLogCallinstead of aLogDefinition. 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'sMatchingCall(log => ...)is unchanged. Migration:LogFilter.MatchingCall(LogDefinition.Capture(...))becomesLogFilter.MatchingCall(LogCall.Capture(...)).
Added
[assembly: GenerateLogDefinitions(typeof(T))]: a source generator, shipped in the LogAssertions package, writes aLogDefinitionfor each[LoggerMessage]method of the assembly that containsT, at compile time and without reflection. For each type it adds an internal class<Type>LogDefinitionsin the type's namespace with one field per method, so a test writesHasLogged().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 inPlaceholderNames(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 inInternalsVisibleTo; 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(withTypeInAssembly): the assembly attribute that opts a product assembly in, named by any type in it; apply it once per product assembly.- Generator warnings
LOGA001toLOGA004, reported at theGenerateLogDefinitionsattribute: 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 itsDefinition,Properties, andException, forLogFilter.MatchingCall.
Changed
LogContractRenderer.Renderwrites?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 explicitEventId, so a renamed method keeps its event ID.
v0.16.0
[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. WaitForLogAsyncandWaitForLogsAsyncdocumentation points toWillLog(timeout, cancellationToken)for a bounded wait that fails with the captured records.
v0.15.1
[0.15.1] - 2026-11-17: a record a test has seen is in its report
Fixed
AddTeedFakeLoggingandTestOutputLogCollectorBuilder.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.AddTeedFakeLoggingwith a null collector registered the tee before it threwArgumentNullException. It now checks both arguments first and leaves the builder unchanged.
v0.15.0
[0.15.0] - 2026-11-15: event ID allowlist, compact dumps with exceptions, .NET 11
BREAKING
LogCapture.Deconstructwas removed, as 0.14.0 announced. It only turnedvar (factory, collector) = LogCollectorBuilder.Create();into a build error that named the new form; that line now fails with the compiler's own error (CS1061, noDeconstructonLogCapture). Source that compiled against 0.14.x never contained the call, so this changes binary compatibility only. Migration:using var logs = LogCollectorBuilder.Create();, thenlogs.Collector(await using varin async code).LogContractRenderer.Renderoutput 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.0andnet11.0. Each target framework resolves its ownMicrosoft.Extensions.Diagnostics.Testing(10.11.0 fornet10.0, 11.0.0 fornet11.0). WithEventIdIn(params int[] eventIds)on every assertion chain (HasLogged,HasNotLogged,HasLoggedSequencesteps,WillLog) andLogFilter.WithEventIdIn(params int[] eventIds): records whose event ID is any of the listed IDs, in place ofLogFilter.Any(LogFilter.WithEventId(a), LogFilter.WithEventId(b)). Duplicates count once. An empty list throwsArgumentException, because a filter that accepts nothing is almost always a mistake and would makeHasNotLogged()pass for no reason. The failure text names the call with its distinct IDs and describes the filter asEventId in {1, 2}, with braces, so it is not taken for the range ofWithEventIdInRange.DumpVerbosity.CompactWithException(value 3, appended afterVerbose; the values of the other members did not change): theCompactheadline of each record plus oneexception: Type: messageline for a record that carries an exception, with no properties and no scopes. It works withDumpTo,DumpToTestOutput, and bothDumpToTestOutputOnFailureoverloads; a dump of 46 records, three of them with an exception, is 49 lines.
Changed
TUnit.AssertionsandTUnit.Coreminimum versions raised from 1.81.10 to 1.85.0: 1.83.0 is the first TUnit with anet11.0asset, and 1.85.0 keeps TUnit's OpenTelemetry and ASP.NET Core packages on OpenTelemetry 1.20.x fornet10.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.RunwithinExecutionContext.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 ofAddTeedFakeLoggingas 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", showsWithEventName(...).WithMessageTemplate(...)for a record the contract renderer cannot reach; the troubleshooting entry for the removedDeconstructnames 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. Theexception:line now shows the message on one line, each line break replaced by a space;Verbosestill 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.
LogSnapshotRendereris unchanged: it writes the captured text verbatim, as documented. - Filter descriptions and the allowlist (the
matching:andStep filters:clauses of a failure, the filter named by a canceled wait, and theAllowed definitions:lines ofHasLoggedOnly) 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
[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.AssertionsandTUnit.Coreminimum versions raised from 1.80.0 to 1.81.10.- README: a record logged in a test class's
DisposeAsyncis 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" underOnce(). The records the collector holds when the wait ends now decide.FakeLogCollector.WaitForLogAsyncandWaitForLogsAsyncthrewOperationCanceledExceptionwhen 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 theILogRecordFilterdocs now say so (keep custom filters free of side effects).
v0.14.0
[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)andTestOutputLogCollectorBuilder.CreateTeed(LogLevel)return aLogCaptureinstead of a(Factory, Collector)tuple, sovar (factory, collector) = LogCollectorBuilder.Create();and.Factorymember access no longer compile (.Collectorstill 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 uselogsas theILoggerFactoryandlogs.Collectorfor assertions.LogCaptureis alsoIAsyncDisposable, so in async code writeawait using var logs = ...; analyzers such as Roslynator RCS1261 and Meziantou MA0042 report a plainusingor an explicitDispose()call there.FakeLoggingBuilderExtensions.AddTeedFakeLogginglost itsILoggerProvider? teeProviderparameter, 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)fromTUnit.Logging.Microsoft.HasLogged()counts that admit zero (Never(),AtMost(n),Exactly(0),Between(0, n), and theHasLoggedAtMost(n)/HasLoggedExactly(0)/HasLoggedBetween(0, n)shorthands) fail as vacuous when every level the chain targets sits below the collector's capture floor, asHasNotLogged()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 itsFakeLogCollectorin one disposable object. It implementsILoggerFactory(pass it wherever a factory is expected) andIAsyncDisposable; disposing it disposes the factory and its providers, including one added withAddProvider, and the collector keeps its records. Disposal does not stop capture: a logger created before keeps writing into the collector.- Its
Deconstructexists 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.
- Its
LogCollectorBuilder.Create(TimeProvider timeProvider, LogLevel minimumLevel = LogLevel.Trace)andTestOutputLogCollectorBuilder.CreateTeed(TimeProvider timeProvider, LogLevel minimumLevel = LogLevel.Trace): the collector stamps each record withtimeProvider's time, soAtMostOncePerand 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, elseTimeProvider.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 enablesDumpToTestOutputOnFailure()and makes the tee's routing exact. All its state is static and keyed weakly by the test'sTestContext. 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 ofHasLogged(), built onWaitForLogsAsync.- 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
timeoutor the token ends the wait, it fails with the expectation, the count, and the captured records, not a bare cancellation. Thetimeoutis 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, plusGetMatch()andGetMatches(), which run the assertion; insideAssert.Multiple(), after a failed wait they throwInvalidOperationExceptionnaming the failure. There is noNever()orAtMost(n), since a wait cannot prove absence.
HasLogged()...AtMostOncePer(TimeSpan interval): every gap between consecutive matching records, ordered byFakeLogRecord.Timestamp(the collector's clock), must be at leastinterval: two records exactlyintervalapart 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()andDumpToTestOutputOnFailure(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
InvalidOperationExceptionwith the line to add.
TestOutputLogCollectorBuilder.CreateTeedDiscarding(LogLevel minimumLevel = LogLevel.Trace): an enabledILoggerFactorythat 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 example1201 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.AssertionsandTUnit.Coreminimum 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
WillLoginstead of polling withEventually, 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 byWithEventId/WithEventName, without making theminternal. - Corrected claims:
- disposing the factory does not stop capture;
AssertAllAsyncneeds `using LogAssertions.T...
v0.13.1
[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.CreateDiscardingloggers returnednullfromBeginScope. TheILoggercontract allows that, butNullLoggerand the common production loggers return a scope, so code that requires a scope instance passed in production and threw under a discarding logger.BeginScopenow returns a shared scope whose disposal does nothing.
v0.13.0
[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 onFakeLogCollector.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 theOperationCanceledExceptionsays 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 forcountmatching records and returns them in the order they were logged.LogCollectorBuilder.CreateDiscarding(LogLevel minimumLevel = LogLevel.Trace)returns anILoggerFactorywhose loggers are enabled atminimumLeveland above but keep nothing, so code guarded bylogger.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>[])andWhen(bool, Func<TSelf, TSelf>)(on everyHasLogged/HasNotLogged/HasLoggedSequencechain) take configurators that return the assertion, which is what an expression lambda such ass => 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 existingActionoverloads, with the same semantics. AThenAnyOrdercall that mixes a statement lambda with expression lambdas binds as a whole to theActionoverload, 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; passArray.Empty<Action<HasLoggedSequenceAssertion>>()instead.ThenAnyOrder(null)andWhen(condition, null)with a barenullneed a cast to theActionorFunctype to choose an overload. Calls that pass lambdas are unaffected. TUnit.AssertionsandTUnit.Coreminimum versions raised from 1.58.0 to 1.77.0, andMicrosoft.Extensions.Diagnostics.Testingfrom 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
WaitForLogAsyncinstead of polling withEventually; theHasLoggedOnlysection 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.Loggingis compared with collector capture.
v0.12.0
[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 abovefloorcarries 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 noAllowing(...)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 guardHasNotLogged()already had.MatchingAny(LogDefinition, params LogDefinition[])on the assertion chains, andLogFilter.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)onHasLoggedSequence()adds a strictly-ordered typed step, so a flow reads as one call per event (.Step(OrderReceived).Step(PaymentCaptured).Step(OrderShipped)) instead of alternatingMatching(...)andThen(). Further filters chain onto the step just opened.
Changed
- Documented where
[LoggerMessage]definitions must live to be assertable:internal(with[InternalsVisibleTo]) orpublic, and not on a generic type. Roslynator'sRCS1158ignores private members, so a private definition on a generic base compiles until it is promoted tointernalfor typed capture, at which point the build breaks; hosting definitions in a non-genericstatic partial classresolves it and reads better at the capture site. Also documented that negative assertions gain the most from typed definitions (a substringHasNotLogged()silently passes once the wording drifts; an identity-keyed one cannot), and when to reach for a renderedLogSnapshotRenderersnapshot instead.
v0.11.0
[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 anIsEnabledgate inside generated logging code cannot suppress the capture. A lambda that logs zero or multiple records fails fast with an explanatoryArgumentException. Argument values in the capture lambda are throwaway; store definitions instatic readonlyfields.Matching(LogDefinition)on theHasLogged()/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: chainWithProperty(...)to pin placeholder values andAtLevel(...)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)andLogFilter.MatchingCall(LogDefinition)exposed the same matching as composableILogRecordFilterfactories for reuse viaWithFilter(...)andLogFilter.All/Any/Not.
Changed
LogFilter.Matching(null!)call sites became ambiguous between theRegexandLogDefinitionoverloads; a null-literal argument needs a cast to pick one. Compiled code is unaffected.