skip to content

In an ASP.NET Core 10 service logging thousands of pick events per second, what does [LoggerMessage] generate, and when do you still need an ILogger.IsEnabled guard?

level: seniorimportance: should knowfreq 40%

answer

  1. params object?[] allocated before the level check
  2. static partial void, partial class
  3. generated IsEnabled check, SkipEnabledCheck
  4. argument expressions still run first
  5. CA1848, CA1873, SYSLIB1015

basics

~20 s

[LoggerMessage] on a partial method makes the compiler generate a strongly typed logging method that checks IsEnabled and logs without an object array or boxing. Arguments are still evaluated by the caller, so expensive ones need an explicit IsEnabled guard.

solid answer

~50 s

A call such as `LogDebug("Scanned {Sku} at {Bin}", sku, bin)` allocates a `params object?[]`, boxes value types and builds the state before `Logger.Log` checks each provider's level, so a disabled Debug line still costs allocations on every pick. Declaring `[LoggerMessage(Level = LogLevel.Debug, Message = "Scanned {Sku} at {Bin}")] static partial void Scanned(ILogger logger, string sku, int bin);` in a `partial` class lets the source generator write the body at build time: it checks `logger.IsEnabled` first (unless `SkipEnabledCheck = true`), parses the template once and passes the values strongly typed. It also gives every event an `EventId` and an `EventName` (the method name by default) and reports mistakes at compile time, such as SYSLIB1015 for a parameter missing from the template. What it cannot do is stop C# from evaluating the arguments: `JsonSerializer.Serialize(order)` runs before the call, so guard it with `if (logger.IsEnabled(LogLevel.Debug))`, the fix CA1873 suggests.

code

csharp · 10 lines
csharp
public sealed partial class ScanHandler(ILogger<ScanHandler> logger)
{
    public void Handle(string sku, int bin)
    {
        LogScanned(sku, bin);   // logger taken from the primary constructor (.NET 9+)
    }

    [LoggerMessage(Level = LogLevel.Debug, Message = "Scanned {Sku} at bin {Bin}")]
    private partial void LogScanned(string sku, int bin);
}

go deeper

for a junior

Recall that [LoggerMessage] goes on a partial method in a partial class and that the build generates its body.

for a middle

Explain what an ordinary LogDebug call allocates even when disabled, and what the generated method does differently.

for a senior

Show where IsEnabled guards still matter, when SkipEnabledCheck is safe, and how you would prove the gain with allocation measurements on the hot path.

for a principal

Decide where the team draws the line between readable extension calls and generated log methods, and how event ids are allocated across services.

## What an ordinary call costs The `LogInformation`, `LogDebug` and similar methods are extension methods on `ILogger` taking `string? message, params object?[] args`. For every call, whether or not the level is enabled: 1. The C# compiler evaluates each argument expression and allocates the `object?[]` for the `params` parameter. 2. Each value-type argument (`int`, `decimal`, `Guid`, `DateTimeOffset`) is **boxed** into that array. 3. The extension wraps message and array in a `FormattedLogValues` state and calls `ILogger.Log`. 4. Only then does `Logger.Log` check each provider's minimum level and return if none is interested. The template itself is parsed once and cached, but steps 1 to 3 repeat on every call. A picking service that logs each scan at `Debug` pays them thousands of times per second while `Debug` is switched off in production. The CA1848 analyzer ("Use the LoggerMessage delegates") exists to point at those calls; it is not enabled by default. ## What [LoggerMessage] generates ```csharp namespace Warehouse.Picking; internal static partial class PickLog { [LoggerMessage(EventId = 4101, Level = LogLevel.Debug, Message = "Scanned {Sku} at bin {Bin}")] public static partial void Scanned(this ILogger logger, string sku, int bin); [LoggerMessage(EventId = 4102, Level = LogLevel.Warning, Message = "Short pick on order {OrderId}: {Missing} missing")] public static partial void ShortPick(this ILogger logger, Exception? ex, int orderId, int missing); } ``` `LoggerMessageAttribute` (namespace `Microsoft.Extensions.Logging`) marks a `partial` method returning `void`; the source generator in the logging abstractions package writes its body at build time. The generated code: - checks `logger.IsEnabled(level)` and returns early, **unless** `SkipEnabledCheck = true`; - passes the arguments **strongly typed**, without a `params` array and without boxing them for the call, and parses the template once; - sets the entry's `EventId` and `EventName` (`EventName` defaults to the method name); - treats the first `ILogger`, `LogLevel` and `Exception` parameters specially: the exception becomes the entry's exception, a `LogLevel` parameter makes the level dynamic when the attribute omits it. Forms the generator accepts: | Form | Where the logger comes from | |---|---| | `static partial void M(ILogger logger, ...)` | the parameter | | `static partial void M(this ILogger logger, ...)` | the extension receiver | | instance `partial void M(...)` | an `ILogger` field, or since .NET 9 a primary-constructor parameter | Mistakes surface as compiler diagnostics: SYSLIB1015 when a parameter is not referenced in the message, SYSLIB1006 when two methods in a class share an event id. ## The older API it replaces Before the generator, the same effect needed `LoggerMessage.Define<T1, ...>(level, eventId, template)`, which returns a cached `Action<ILogger, T1, ..., Exception?>` that also checks `IsEnabled` (unless `LogDefineOptions.SkipEnabledCheck`). It supports at most six template values and no dynamic level, and every delegate is hand-written boilerplate. Source-generated methods are the current form; `Define` still appears in older code and in libraries targeting old frameworks. ## When IsEnabled is still needed The generated check runs **inside** the method. C# evaluates the arguments **before** the call: ```csharp // Serialize runs on every pick, even with Debug off logger.OrderSnapshot(JsonSerializer.Serialize(order)); // Guarded: the expensive argument is built only when someone will read it if (logger.IsEnabled(LogLevel.Debug)) { logger.OrderSnapshot(JsonSerializer.Serialize(order)); } ``` Use an explicit guard when an argument is costly to compute: serialising an object, summing collection contents, formatting a report. The .NET 10 analyzers include **CA1873** "Avoid potentially expensive logging", reported as a suggestion, for exactly this case. When the call site already guards, `SkipEnabledCheck = true` on the method removes the duplicate check. `IsEnabled` itself is cheap: the logger holds the chosen minimum level per provider and compares against it. Even with `SkipEnabledCheck`, an entry below a provider's level is still not written, because `Logger.Log` filters per provider; the flag only drops the early return. ## Putting it together - Use ordinary extension methods for rare events where clarity beats nanoseconds. - Use `[LoggerMessage]` for events on hot paths and for any event you want stable `EventId`s on. - Add `IsEnabled` guards only around expensive arguments, not around every call. - Measure before and after: allocation counts in a benchmark or a memory profiler show the difference better than intuition.

  • What does SkipEnabledCheck = true change, and when would you set it?
    It removes the early `IsEnabled` return from the generated body. Set it when every caller already guards with `IsEnabled` because an argument is expensive, so the level is not checked twice. Entries below a provider's minimum are still dropped, because `Logger.Log` filters per provider regardless.
  • How does a [LoggerMessage] method decide which parameter is the exception and whether the level is fixed?
    The generator treats the first `ILogger`, `LogLevel` and `Exception` parameters specially. The first `Exception` becomes the entry's exception rather than a template value, and when the attribute omits `Level`, a `LogLevel` parameter supplies it at run time. Later parameters of those types are ordinary template values.
  • Why do [LoggerMessage] methods help log consumers as well as CPU usage?
    Each method carries a fixed `EventId` and `EventName`, and the template is a constant, so every occurrence of the event is identical in shape. Dashboards and alerts can match on the event id instead of a sentence, and SYSLIB1006 stops two methods in one class from sharing an id.

  • LogDebug returns before evaluating anything when Debug is disabled.
  • [LoggerMessage] stops the arguments from being evaluated when the level is off.
  • The generator only emits an IsEnabled check when SkipEnabledCheck is true.
  • LoggerMessage.Define is the current recommended way to write new log methods.
  • Logging templates are re-parsed on every call, so caching them by hand is required.

Assumes .NET 10: instance [LoggerMessage] methods can take the logger from a primary-constructor parameter since .NET 9, and the .NET 10 analyzers report CA1873 as a suggestion.