Table of Contents

Class LogAssertionBase<TSelf>

Namespace
LogAssertions.TUnit
Assembly
LogAssertions.TUnit.dll

Shared base class for HasLoggedAssertion, HasNotLoggedAssertion, and HasLoggedSequenceAssertion. Implements the filter chain (level, message, exception, structured-state, scope, event, and arbitrary-predicate filters) and the failure-message snapshot rendering. Derived classes own count-expectation semantics and the [AssertionExtension] attribute that registers the entry-point name.

public abstract class LogAssertionBase<TSelf> : Assertion<FakeLogCollector>, IAssertion where TSelf : LogAssertionBase<TSelf>

Type Parameters

TSelf

The derived assertion type, returned from filter methods to enable fluent chaining.

Inheritance
Assertion<FakeLogCollector>
LogAssertionBase<TSelf>
Implements
IAssertion
Derived
Inherited Members
Assertion<FakeLogCollector>.Context
Assertion<FakeLogCollector>.CheckAsync(EvaluationMetadata<FakeLogCollector>)
Assertion<FakeLogCollector>.GetExpectation()
Assertion<FakeLogCollector>.AssertAsync()
Assertion<FakeLogCollector>.GetAwaiter()
Assertion<FakeLogCollector>.ThrowIfMixingCombiner<TCombinerToAvoid>()
Assertion<FakeLogCollector>.CreateException(AssertionResult)
Assertion<FakeLogCollector>.InternalWrappedExecution
Assertion<FakeLogCollector>.And
Assertion<FakeLogCollector>.Or

Remarks

Not for external derivation. This type is public only because the curiously-recurring template pattern (CRTP) used here requires public visibility wherever the public sealed derived classes (HasLoggedAssertion etc.) appear. The shape of this base class: protected members, virtual hooks, internal helpers: is implementation detail and may change in any release. Do not derive from it; do not reference its protected members from outside this assembly. The supported public surface is the entry-point extension methods on FakeLogCollector plus the fluent chain methods returning TSelf.

See the README "Stability promise" section for the full surface-stability contract.

Constructors

LogAssertionBase(AssertionContext<FakeLogCollector>)

Initialises the base assertion with the supplied TUnit context.

protected LogAssertionBase(AssertionContext<FakeLogCollector> context)

Parameters

context AssertionContext<FakeLogCollector>

The assertion context supplied by TUnit.

Methods

AddFilter(ILogRecordFilter)

Records a filter. Default implementation appends to the shared filter chain used by single-match assertions; HasLoggedSequenceAssertion overrides this to route filters into the current sequence step.

protected virtual void AddFilter(ILogRecordFilter filter)

Parameters

filter ILogRecordFilter

The filter to add.

Exceptions

ArgumentNullException

filter is null.

AppendCapturedRecords(StringBuilder, IReadOnlyList<FakeLogRecord>)

Appends the captured-records section to sb; delegates to LogAssertionRendering.AppendCapturedRecords so the same rendering is available to the public FakeLogCollector.DumpTo(...) extension.

protected static void AppendCapturedRecords(StringBuilder sb, IReadOnlyList<FakeLogRecord> snapshot)

Parameters

sb StringBuilder

The target string builder.

snapshot IReadOnlyList<FakeLogRecord>

All captured records.

Exceptions

ArgumentNullException

A required argument is null.

AppendFilterSummary(StringBuilder)

Appends the human-readable filter chain (e.g. matching: Level = Warning, Message contains "x") to sb. Emits nothing if no filters have been added.

protected void AppendFilterSummary(StringBuilder sb)

Parameters

sb StringBuilder

The target string builder for the expectation message.

Exceptions

ArgumentNullException

sb is null.

AtAnyLevel(params LogLevel[])

Filters to records whose level is one of levels.

public TSelf AtAnyLevel(params LogLevel[] levels)

Parameters

levels LogLevel[]

The set of log levels to match. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

levels is null.

AtLevel(LogLevel)

Filters to records at the specified level.

public TSelf AtLevel(LogLevel level)

Parameters

level LogLevel

The exact log level to match.

Returns

TSelf

This assertion for chaining.

AtLevelOrAbove(LogLevel)

Filters to records whose level is greater than or equal to level.

public TSelf AtLevelOrAbove(LogLevel level)

Parameters

level LogLevel

The minimum log level to match (inclusive).

Returns

TSelf

This assertion for chaining.

AtLevelOrBelow(LogLevel)

Filters to records whose level is less than or equal to level.

public TSelf AtLevelOrBelow(LogLevel level)

Parameters

level LogLevel

The maximum log level to match (inclusive).

Returns

TSelf

This assertion for chaining.

BuildFailureMessage(int, IReadOnlyList<FakeLogRecord>)

Renders the matching summary plus a snapshot of every captured record (level, category, message, structured properties, scopes, exception) for use in failure messages.

protected static string BuildFailureMessage(int matchCount, IReadOnlyList<FakeLogRecord> snapshot)

Parameters

matchCount int

The number of matching records.

snapshot IReadOnlyList<FakeLogRecord>

All captured records.

Returns

string

The multi-line failure message body.

Exceptions

ArgumentNullException

snapshot is null.

Containing(string, StringComparison)

Filters to records whose message contains substring using the specified comparison. The comparison is explicit by design: pass Ordinal for the most common case.

public TSelf Containing(string substring, StringComparison comparison)

Parameters

substring string

The substring to search for. Must be non-null.

comparison StringComparison

The string comparison to apply.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

substring is null.

ContainingAll(StringComparison, params string[])

Filters to records whose message contains every one of substrings.

public TSelf ContainingAll(StringComparison comparison, params string[] substrings)

Parameters

comparison StringComparison

The string comparison to apply.

substrings string[]

The substrings; the message must contain all of them.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

substrings is null.

ContainingAny(StringComparison, params string[])

Filters to records whose message contains at least one of substrings.

public TSelf ContainingAny(StringComparison comparison, params string[] substrings)

Parameters

comparison StringComparison

The string comparison to apply.

substrings string[]

The substrings; the message must contain at least one.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

substrings is null.

CountMatches(IReadOnlyList<FakeLogRecord>)

Counts records in snapshot that satisfy every filter in the chain.

protected int CountMatches(IReadOnlyList<FakeLogRecord> snapshot)

Parameters

snapshot IReadOnlyList<FakeLogRecord>

The captured records to evaluate.

Returns

int

The number of matching records.

Exceptions

ArgumentNullException

snapshot is null.

ExcludingCategory(string)

Filters to records whose category is not category.

public TSelf ExcludingCategory(string category)

Parameters

category string

The category name to exclude. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

category is null.

ExcludingLevel(LogLevel)

Filters to records whose level is not level (alias for NotAtLevel(LogLevel)).

public TSelf ExcludingLevel(LogLevel level)

Parameters

level LogLevel

The log level to exclude.

Returns

TSelf

This assertion for chaining.

GetMatches(IReadOnlyList<FakeLogRecord>)

Returns the matching records from snapshot as a snapshot list (a defensive copy not bound to the live collector).

protected IReadOnlyList<FakeLogRecord> GetMatches(IReadOnlyList<FakeLogRecord> snapshot)

Parameters

snapshot IReadOnlyList<FakeLogRecord>

The captured records to evaluate.

Returns

IReadOnlyList<FakeLogRecord>

The matched records in original order.

Exceptions

ArgumentNullException

snapshot is null.

Matching(Regex)

Filters to records whose message matches the regular expression pattern.

public TSelf Matching(Regex pattern)

Parameters

pattern Regex

The compiled regex. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

pattern is null.

MatchingAll(params ILogRecordFilter[])

Adds a conjunction (AND) of filters as a single composite filter on the chain. Equivalent to chaining the filters individually but useful when composing pre-built reusable filters.

public TSelf MatchingAll(params ILogRecordFilter[] filters)

Parameters

filters ILogRecordFilter[]

The conjunction's children. May be empty (matches every record).

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

filters is null.

MatchingAny(params ILogRecordFilter[])

Adds a disjunction (OR) of filters as a single composite filter on the chain. The chain itself is AND-combined; this method composes a sub-disjunction inside that AND, enabling expressions such as .AtLevel(Warning).MatchingAny(LogFilter.Containing("a", Ordinal), LogFilter.Containing("b", Ordinal)) = level == Warning AND (msg contains "a" OR msg contains "b").

public TSelf MatchingAny(params ILogRecordFilter[] filters)

Parameters

filters ILogRecordFilter[]

The disjunction's children. May be empty (matches no record).

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

filters is null.

Not(ILogRecordFilter)

Adds the negation of filter to the chain. A record matches when the inner filter does not.

public TSelf Not(ILogRecordFilter filter)

Parameters

filter ILogRecordFilter

The filter to negate. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

filter is null.

NotAtLevel(LogLevel)

Filters to records whose level is not level.

public TSelf NotAtLevel(LogLevel level)

Parameters

level LogLevel

The log level to exclude.

Returns

TSelf

This assertion for chaining.

NotContaining(string, StringComparison)

Filters to records whose message does not contain substring.

public TSelf NotContaining(string substring, StringComparison comparison)

Parameters

substring string

The substring that must not appear. Must be non-null.

comparison StringComparison

The string comparison.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

substring is null.

When(bool, Action<TSelf>)

Conditionally applies apply to this assertion. When condition is true, runs the configurator and returns this for chaining; when false, returns this unchanged. Useful in parameterised tests to avoid branching the entire assertion chain on a boolean: .HasLogged().AtLevel(Warning).When(expectRetry, b => b.Containing("retry", Ordinal)).AtLeast(1).

public TSelf When(bool condition, Action<TSelf> apply)

Parameters

condition bool

When true, applies the configurator.

apply Action<TSelf>

The configurator. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

apply is null.

Where(Func<FakeLogRecord, bool>)

Escape-hatch filter that applies an arbitrary predicate to each record. Use only when no other filter expresses the constraint cleanly.

public TSelf Where(Func<FakeLogRecord, bool> predicate)

Parameters

predicate Func<FakeLogRecord, bool>

A predicate applied to each Microsoft.Extensions.Logging.Testing.FakeLogRecord. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

predicate is null.

WithCategory(string)

Filters to records emitted by a logger whose category name equals category (ordinal comparison).

public TSelf WithCategory(string category)

Parameters

category string

The full category name (typically the logger name) to match. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

category is null.

WithEventId(int)

Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Id ID equals eventId.

public TSelf WithEventId(int eventId)

Parameters

eventId int

The numeric event ID to match.

Returns

TSelf

This assertion for chaining.

WithEventIdInRange(int, int)

Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Id ID is within the inclusive range min..max.

public TSelf WithEventIdInRange(int min, int max)

Parameters

min int

The minimum event ID (inclusive).

max int

The maximum event ID (inclusive).

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentOutOfRangeException

max is less than min.

WithEventName(string)

Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Id name equals eventName (ordinal).

public TSelf WithEventName(string eventName)

Parameters

eventName string

The event name (the second argument of EventId) to match. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

eventName is null.

WithException()

Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Exception is non-null (any type).

public TSelf WithException()

Returns

TSelf

This assertion for chaining.

WithException(Func<Exception, bool>)

Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Exception satisfies predicate.

public TSelf WithException(Func<Exception, bool> predicate)

Parameters

predicate Func<Exception, bool>

A predicate over the (non-null) exception. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

predicate is null.

WithExceptionMessage(string, StringComparison)

Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Exception is non-null and whose Message contains substring under the supplied comparison.

public TSelf WithExceptionMessage(string substring, StringComparison comparison)

Parameters

substring string

The substring to search for in the exception's message. Must be non-null.

comparison StringComparison

The string comparison rules. Project convention: pass explicitly.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

substring is null.

WithException<TException>()

Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Exception is assignable to TException.

public TSelf WithException<TException>() where TException : Exception

Returns

TSelf

This assertion for chaining.

Type Parameters

TException

The exception type to match.

WithFilter(ILogRecordFilter)

Adds a user-supplied ILogRecordFilter to the chain. Use this to plug in composable filter objects built via LogFilter factory methods, or implementations of ILogRecordFilter shared across many tests.

public TSelf WithFilter(ILogRecordFilter filter)

Parameters

filter ILogRecordFilter

The filter. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

filter is null.

WithInnerExceptionMessage(string, StringComparison)

Filters to records whose InnerException's Message contains substring under the supplied comparison. Walks only one level.

public TSelf WithInnerExceptionMessage(string substring, StringComparison comparison)

Parameters

substring string

The substring to search for in the inner exception's message. Must be non-null.

comparison StringComparison

The string comparison rules. Project convention: pass explicitly.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

substring is null.

WithInnerException<TInner>()

Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Exception wraps an InnerException assignable to TInner. Walks only one level (does not search deeper inner exceptions). Designed for the gRPC / RPC pattern where a transport exception (e.g. RpcException) wraps the underlying domain exception once.

public TSelf WithInnerException<TInner>() where TInner : Exception

Returns

TSelf

This assertion for chaining.

Type Parameters

TInner

The inner-exception type to match.

WithLoggerName(string)

Alias for WithCategory(string) using the more colloquial name.

public TSelf WithLoggerName(string loggerName)

Parameters

loggerName string

The full logger name (the category). Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

loggerName is null.

WithMessage(Func<string, bool>)

Filters to records whose message satisfies predicate.

public TSelf WithMessage(Func<string, bool> predicate)

Parameters

predicate Func<string, bool>

A predicate applied to the log message. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

predicate is null.

WithMessageTemplate(string)

Filters to records whose original message template (the pre-substitution form, e.g. "Order {OrderId} processed") equals template exactly (ordinal).

public TSelf WithMessageTemplate(string template)

Parameters

template string

The exact message template to match. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

template is null.

WithProperty(string, Func<string?, bool>)

Filters to records containing a structured-state entry with the specified key whose formatted string value satisfies predicate.

public TSelf WithProperty(string key, Func<string?, bool> predicate)

Parameters

key string

The structured-state key. Must be non-null.

predicate Func<string, bool>

A predicate applied to the formatted string value. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

A required argument is null.

WithProperty(string, string?)

Filters to records containing a structured-state entry with the specified key and value (ordinal string comparison on the formatted value).

public TSelf WithProperty(string key, string? value)

Parameters

key string

The structured-state key. Must be non-null.

value string

The expected string value (ordinal comparison); may be null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

key is null.

WithProperty<T>(string, Func<T, bool>)

Filters to records whose structured-state value at key parses to a T satisfying predicate.

public TSelf WithProperty<T>(string key, Func<T, bool> predicate) where T : IParsable<T>

Parameters

key string

The structured-state key. Must be non-null.

predicate Func<T, bool>

A predicate over the parsed typed value. Must be non-null.

Returns

TSelf

This assertion for chaining.

Type Parameters

T

The parsable value type. Must implement IParsable<TSelf>.

Remarks

The stored string is parsed back to T using InvariantCulture; a value that is absent or does not parse never matches.

Exceptions

ArgumentNullException

A required argument is null.

WithProperty<T>(string, T)

Filters to records whose structured-state value at key parses to a T equal to value (compared via Default).

public TSelf WithProperty<T>(string key, T value) where T : IParsable<T>

Parameters

key string

The structured-state key. Must be non-null.

value T

The expected typed value.

Returns

TSelf

This assertion for chaining.

Type Parameters

T

The parsable value type. Must implement IParsable<TSelf>.

Remarks

FakeLogRecord stores structured-state values as their formatted strings; this overload parses the stored string back to T using InvariantCulture, removing the manual int.TryParse(...) boilerplate at the call site. A value that is absent or does not parse never matches.

Exceptions

ArgumentNullException

key is null.

WithScopeProperties(IReadOnlyDictionary<string, object?>)

Filters to records whose active scopes collectively contain every key/value pair in required (subset match: each pair must match in some scope; different pairs may match in different scopes).

public TSelf WithScopeProperties(IReadOnlyDictionary<string, object?> required)

Parameters

required IReadOnlyDictionary<string, object>

The required scope-property key/value pairs. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

required is null.

WithScopeProperty(string)

Filters to records emitted while a scope on the calling logger contained a property with the specified key, regardless of its value.

public TSelf WithScopeProperty(string key)

Parameters

key string

The scope-property key. Must be non-null.

Returns

TSelf

This assertion for chaining.

Remarks

Asserts only that the scope key is present, not its value. Use when the value is set internally and is not known to the test (for example a caller-info scope). Pairs with HasNotLogged() to assert a scope key was never attached. A scope property whose value is null still counts as present.

Exceptions

ArgumentNullException

key is null.

WithScopeProperty(string, Func<object?, bool>)

Filters to records emitted while a scope on the calling logger contained a property with the specified key whose value satisfies predicate.

public TSelf WithScopeProperty(string key, Func<object?, bool> predicate)

Parameters

key string

The scope-property key. Must be non-null.

predicate Func<object, bool>

A predicate applied to the scope-property value. Must be non-null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

A required argument is null.

WithScopeProperty(string, object?)

Filters to records emitted while a scope on the calling logger contained a property with the specified key and value (compared via Equals(object, object)).

public TSelf WithScopeProperty(string key, object? value)

Parameters

key string

The scope-property key. Must be non-null.

value object

The expected scope-property value; may be null.

Returns

TSelf

This assertion for chaining.

Exceptions

ArgumentNullException

key is null.

WithScopeProperty<T>(string, Func<T, bool>)

Filters to records whose active scopes contain a property at key whose value is a T satisfying predicate.

public TSelf WithScopeProperty<T>(string key, Func<T, bool> predicate)

Parameters

key string

The scope-property key. Must be non-null.

predicate Func<T, bool>

A predicate over the typed scope value. Must be non-null.

Returns

TSelf

This assertion for chaining.

Type Parameters

T

The scope-property value type.

Remarks

A scope value whose runtime type is not T never reaches the predicate.

Exceptions

ArgumentNullException

A required argument is null.

WithScopeProperty<T>(string, T)

Filters to records whose active scopes contain a property at key whose value is a T equal to value (compared via Default).

public TSelf WithScopeProperty<T>(string key, T value)

Parameters

key string

The scope-property key. Must be non-null.

value T

The expected typed value.

Returns

TSelf

This assertion for chaining.

Type Parameters

T

The scope-property value type.

Remarks

Scope values keep their runtime type, so this compares typed-to-typed and avoids the boxing-comparison boilerplate of the WithScopeProperty(string, object?) object overload. A scope value of a different runtime type never matches.

Exceptions

ArgumentNullException

key is null.

WithScope<TScope>()

Filters to records emitted while a scope of type TScope was active on the calling logger (matched against Microsoft.Extensions.Logging.Testing.FakeLogRecord.Scopes).

public TSelf WithScope<TScope>()

Returns

TSelf

This assertion for chaining.

Type Parameters

TScope

The scope state type to match.

WithoutException()

Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Exception is null.

public TSelf WithoutException()

Returns

TSelf

This assertion for chaining.

Remarks

The complement of WithException(). Use when a code path logs at a warning/error level but deliberately omits the exception object, and the test needs to assert that no exception was attached.