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
TSelfThe derived assertion type, returned from filter methods to enable fluent chaining.
- Inheritance
-
Assertion<FakeLogCollector>LogAssertionBase<TSelf>
- Implements
-
IAssertion
- Derived
- Inherited Members
-
Assertion<FakeLogCollector>.ContextAssertion<FakeLogCollector>.CheckAsync(EvaluationMetadata<FakeLogCollector>)Assertion<FakeLogCollector>.GetExpectation()Assertion<FakeLogCollector>.AssertAsync()Assertion<FakeLogCollector>.GetAwaiter()Assertion<FakeLogCollector>.ThrowIfMixingCombiner<TCombinerToAvoid>()Assertion<FakeLogCollector>.CreateException(AssertionResult)Assertion<FakeLogCollector>.InternalWrappedExecutionAssertion<FakeLogCollector>.AndAssertion<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
contextAssertionContext<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
filterILogRecordFilterThe filter to add.
Exceptions
- ArgumentNullException
filteris 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
sbStringBuilderThe target string builder.
snapshotIReadOnlyList<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
sbStringBuilderThe target string builder for the expectation message.
Exceptions
- ArgumentNullException
sbis null.
AtAnyLevel(params LogLevel[])
Filters to records whose level is one of levels.
public TSelf AtAnyLevel(params LogLevel[] levels)
Parameters
levelsLogLevel[]The set of log levels to match. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
levelsis null.
AtLevel(LogLevel)
Filters to records at the specified level.
public TSelf AtLevel(LogLevel level)
Parameters
levelLogLevelThe 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
levelLogLevelThe 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
levelLogLevelThe 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
matchCountintThe number of matching records.
snapshotIReadOnlyList<FakeLogRecord>All captured records.
Returns
- string
The multi-line failure message body.
Exceptions
- ArgumentNullException
snapshotis 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
substringstringThe substring to search for. Must be non-null.
comparisonStringComparisonThe string comparison to apply.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
substringis null.
ContainingAll(StringComparison, params string[])
Filters to records whose message contains every one of substrings.
public TSelf ContainingAll(StringComparison comparison, params string[] substrings)
Parameters
comparisonStringComparisonThe string comparison to apply.
substringsstring[]The substrings; the message must contain all of them.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
substringsis 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
comparisonStringComparisonThe string comparison to apply.
substringsstring[]The substrings; the message must contain at least one.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
substringsis null.
CountMatches(IReadOnlyList<FakeLogRecord>)
Counts records in snapshot that satisfy every filter in the chain.
protected int CountMatches(IReadOnlyList<FakeLogRecord> snapshot)
Parameters
snapshotIReadOnlyList<FakeLogRecord>The captured records to evaluate.
Returns
- int
The number of matching records.
Exceptions
- ArgumentNullException
snapshotis null.
ExcludingCategory(string)
Filters to records whose category is not category.
public TSelf ExcludingCategory(string category)
Parameters
categorystringThe category name to exclude. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
categoryis null.
ExcludingLevel(LogLevel)
Filters to records whose level is not level (alias for NotAtLevel(LogLevel)).
public TSelf ExcludingLevel(LogLevel level)
Parameters
levelLogLevelThe 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
snapshotIReadOnlyList<FakeLogRecord>The captured records to evaluate.
Returns
- IReadOnlyList<FakeLogRecord>
The matched records in original order.
Exceptions
- ArgumentNullException
snapshotis null.
Matching(Regex)
Filters to records whose message matches the regular expression pattern.
public TSelf Matching(Regex pattern)
Parameters
patternRegexThe compiled regex. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
patternis 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
filtersILogRecordFilter[]The conjunction's children. May be empty (matches every record).
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
filtersis 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
filtersILogRecordFilter[]The disjunction's children. May be empty (matches no record).
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
filtersis 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
filterILogRecordFilterThe filter to negate. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
filteris null.
NotAtLevel(LogLevel)
Filters to records whose level is not level.
public TSelf NotAtLevel(LogLevel level)
Parameters
levelLogLevelThe 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
substringstringThe substring that must not appear. Must be non-null.
comparisonStringComparisonThe string comparison.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
substringis 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
conditionboolWhen true, applies the configurator.
applyAction<TSelf>The configurator. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
applyis 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
predicateFunc<FakeLogRecord, bool>A predicate applied to each Microsoft.Extensions.Logging.Testing.FakeLogRecord. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
predicateis null.
WithCategory(string)
Filters to records emitted by a logger whose category name equals category
(ordinal comparison).
public TSelf WithCategory(string category)
Parameters
categorystringThe full category name (typically the logger name) to match. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
categoryis null.
WithEventId(int)
Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Id ID equals eventId.
public TSelf WithEventId(int eventId)
Parameters
eventIdintThe 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
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentOutOfRangeException
maxis less thanmin.
WithEventName(string)
Filters to records whose Microsoft.Extensions.Logging.Testing.FakeLogRecord.Id name equals eventName (ordinal).
public TSelf WithEventName(string eventName)
Parameters
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
eventNameis 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
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
predicateis 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
substringstringThe substring to search for in the exception's message. Must be non-null.
comparisonStringComparisonThe string comparison rules. Project convention: pass explicitly.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
substringis 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
TExceptionThe 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
filterILogRecordFilterThe filter. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
filteris 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
substringstringThe substring to search for in the inner exception's message. Must be non-null.
comparisonStringComparisonThe string comparison rules. Project convention: pass explicitly.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
substringis 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
TInnerThe inner-exception type to match.
WithLoggerName(string)
Alias for WithCategory(string) using the more colloquial name.
public TSelf WithLoggerName(string loggerName)
Parameters
loggerNamestringThe full logger name (the category). Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
loggerNameis null.
WithMessage(Func<string, bool>)
Filters to records whose message satisfies predicate.
public TSelf WithMessage(Func<string, bool> predicate)
Parameters
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
predicateis 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
templatestringThe exact message template to match. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
templateis 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
keystringThe structured-state key. Must be non-null.
predicateFunc<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
keystringThe structured-state key. Must be non-null.
valuestringThe expected string value (ordinal comparison); may be null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
keyis 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
keystringThe structured-state key. Must be non-null.
predicateFunc<T, bool>A predicate over the parsed typed value. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Type Parameters
TThe 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
keystringThe structured-state key. Must be non-null.
valueTThe expected typed value.
Returns
- TSelf
This assertion for chaining.
Type Parameters
TThe 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
keyis 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
requiredIReadOnlyDictionary<string, object>The required scope-property key/value pairs. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
requiredis 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
keystringThe 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
keyis 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
keystringThe scope-property key. Must be non-null.
predicateFunc<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
keystringThe scope-property key. Must be non-null.
valueobjectThe expected scope-property value; may be null.
Returns
- TSelf
This assertion for chaining.
Exceptions
- ArgumentNullException
keyis 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
keystringThe scope-property key. Must be non-null.
predicateFunc<T, bool>A predicate over the typed scope value. Must be non-null.
Returns
- TSelf
This assertion for chaining.
Type Parameters
TThe 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
keystringThe scope-property key. Must be non-null.
valueTThe expected typed value.
Returns
- TSelf
This assertion for chaining.
Type Parameters
TThe 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
keyis 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
TScopeThe 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.