High-performance logging: the cost of LoggerExtensions calls (params object[] allocation, boxing, template parsing), the [LoggerMessage] source generator on partial methods, generated IsEnabled checks and cached delegates, CA1848, guarding expensive arguments with IsEnabled, and a BenchmarkDotNet comparison with MemoryDiagnoser.
A normal call like logger.LogDebug("Item {Id} took {Ms}", id, ms) goes through LoggerExtensions: it allocates a params object[], boxes the int and double, and does that even when Debug is off. The [LoggerMessage] source generator turns a partial method into a strongly typed one: it checks IsEnabled first, uses a cached, pre-parsed template, and passes values without boxing, so a filtered call allocates zero bytes and costs close to nothing (around a nanosecond on typical hardware; benchmark on yours, since absolute numbers vary by CPU and runtime). It also checks at compile time that placeholders match parameters.
You still guard with IsEnabled when computing an argument is expensive, because arguments are evaluated before the call.
The trade-off: more code per event, so use it for hot paths, libraries and your main event catalogue, not every one-off line.
"The convenient extension methods hide some work.
logger.LogDebug("Item {Id} took {Ms} ms", id, ms)compiles to a call with aparams object?[], so every call allocates an array and boxes each value type, before the logger even checks whether Debug is enabled. On a path that runs a hundred thousand times a second, that's a steady stream of garbage for messages nobody reads.The fix built into .NET is the
[LoggerMessage]source generator. I declare apartialmethod with the attribute, giving the event id, level and template, and the generator writes the body at compile time: it callsIsEnabledfirst, and only if the level is on does it call a cached delegate created once with the template already parsed, passing the arguments as typed generics, so there's no array and no boxing on the disabled path. It also gives compile-time checks: if my template has{OrderId}and the method has noorderIdparameter, the build fails with a SYSLIB diagnostic instead of logging the wrong value. For example, at [company] we [moved the logging in a message-processing loop to generated methods and saw allocation rate drop by about X MB/s in dotnet-counters].The mistake I see is thinking the generator makes argument evaluation free. If I write
LogOrderDebug(JsonSerializer.Serialize(order)), the serialisation happens before the method is called. For expensive arguments I still wrap the call inif (logger.IsEnabled(LogLevel.Debug)). And I prove all of this with BenchmarkDotNet andMemoryDiagnoserrather than by assumption. Generated logging is the cheapest correct default for hot paths."
| Approach | Disabled level | Enabled level | Compile-time checks |
|---|---|---|---|
logger.LogInformation("...", a, b) |
Array + boxing allocated, then discarded | Array, boxing, cached template lookup, format | No (CA2254 only checks constancy) |
LoggerMessage.Define<T1,T2> (manual) |
No allocation | No boxing until formatting | No |
[LoggerMessage] generated |
No allocation, ~1 ns | Typed state, cached formatter | Yes: placeholders vs parameters |
if (IsEnabled) ... guard |
Skips argument evaluation | – | – |
| Use generated logging | Plain extension methods are fine |
|---|---|
| Hot loops, middleware, message handlers | Start-up messages, rare errors |
| Libraries other teams consume | Small tools and scripts |
| A central catalogue of event ids | Temporary debugging lines |
In a queue consumer handling [8,000] messages a second, the per-message Debug and Information calls allocated about [180] bytes each through the extension methods. Moving them to [LoggerMessage] methods removed those allocations, cut Gen0 collections from about [40] to [12] per second in dotnet-counters, and lowered p99 processing latency by roughly [15%].
Checks whether the candidate knows the hidden cost of logging calls and the modern, compile-time solution, and measures before optimising.
Green flags
[LoggerMessage] partial method and knows what it generates.Red flags
IsEnabled without understanding why.logger.LogDebug("Item {Id} took {Ms} ms", id, ms);
│ C# compiler
▼
LoggerExtensions.LogDebug(logger, "Item {Id} took {Ms} ms", new object?[] { (object)id, (object)ms });
│ └─ array alloc + 2 boxes, always
▼
logger.Log(LogLevel.Debug, 0, new FormattedLogValues(template, args), null, formatter)
│
▼
Logger.Log → for each provider: if (enabled) provider.Log(...)
The level check happens inside Logger.Log, after the allocations. FormattedLogValues is a struct, but it is passed as a generic TState and the template lookup goes through a cache keyed by the string.
For
[LoggerMessage(EventId = 1001, Level = LogLevel.Debug, Message = "Item {Id} took {Ms} ms")]
public static partial void ItemProcessed(this ILogger logger, int id, double ms);
the generator emits, roughly:
private static readonly Action<ILogger, int, double, Exception?> __ItemProcessedCallback =
LoggerMessage.Define<int, double>(LogLevel.Debug, new EventId(1001, "ItemProcessed"),
"Item {Id} took {Ms} ms", new LogDefineOptions { SkipEnabledCheck = true });
public static partial void ItemProcessed(this ILogger logger, int id, double ms)
{
if (logger.IsEnabled(LogLevel.Debug))
__ItemProcessedCallback(logger, id, ms, null);
}
The template is parsed once into the static delegate. Values travel as int and double inside a generic struct state. For more than six parameters the generator emits its own struct implementing IReadOnlyList<KeyValuePair<string, object?>> instead of Define.
In a partial class with an ILogger field, or (since .NET 8) a primary constructor parameter of type ILogger<T>, you can write instance methods without the ILogger parameter; the generator finds the logger. Static extension methods in a static partial class are the common choice for a shared catalogue.
The generator can't stop C# evaluating Expensive() in logger.ItemProcessed(Expensive(), 1). Guard expensive arguments explicitly, or pass the cheap raw value and let a custom formatter or [LogProperties] (from Microsoft.Extensions.Telemetry.Abstractions) expand it only when enabled.
SYSLIB1xxx diagnostics catch template/parameter mismatches, duplicate event ids in a class, and invalid signatures. CA1848 ("use the LoggerMessage delegates") points at extension-method calls you might convert.
Typical BenchmarkDotNet results on a modern x64 machine with the level disabled: extension method around 15–30 ns and 50–70 bytes per call (array plus boxes); generated method around 1 ns and 0 bytes. With the level enabled, both format the message, but the generated version still avoids the array and boxes. Run the benchmark below on your own hardware; the ratio matters more than the absolute value.
Allocated columns.[LoggerMessage] method and read the SYSLIB diagnostic.dotnet-counters monitor -p <pid> System.Runtime and compare gc-heap-alloc-rate (or dotnet.gc.heap.total_allocated in .NET 9+).A shared event catalogue with the generator, plus a guarded expensive argument.
namespace Shop.Orders;
public sealed record Order(Guid Id, string CustomerId, IReadOnlyList<string> Lines);
// Central catalogue: event ids are unique and searchable
public static partial class OrderLog
{
[LoggerMessage(EventId = 2001, Level = LogLevel.Information, Message = "Order {OrderId} placed for {CustomerId}")]
public static partial void OrderPlaced(this ILogger logger, Guid orderId, string customerId);
[LoggerMessage(EventId = 2002, Level = LogLevel.Debug, Message = "Order {OrderId} line {LineIndex} priced in {ElapsedMs} ms")]
public static partial void LinePriced(this ILogger logger, Guid orderId, int lineIndex, double elapsedMs);
[LoggerMessage(EventId = 2003, Level = LogLevel.Error, Message = "Order {OrderId} failed to save")]
public static partial void SaveFailed(this ILogger logger, Exception ex, Guid orderId);
}
public sealed class OrderPricer(ILogger<OrderPricer> logger)
{
public void Price(Order order)
{
for (var i = 0; i < order.Lines.Count; i++)
{
var start = System.Diagnostics.Stopwatch.GetTimestamp();
// ... pricing work ...
logger.LinePriced(order.Id, i, System.Diagnostics.Stopwatch.GetElapsedTime(start).TotalMilliseconds);
}
// The generator can't skip argument evaluation: guard expensive arguments yourself
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Order dump {Order}", System.Text.Json.JsonSerializer.Serialize(order));
}
logger.OrderPlaced(order.Id, order.CustomerId);
}
}
The benchmark that proves it:
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Microsoft.Extensions.Logging;
BenchmarkRunner.Run<LoggingBenchmarks>();
[MemoryDiagnoser]
public partial class LoggingBenchmarks
{
private readonly ILogger _logger = LoggerFactory
.Create(b => b.SetMinimumLevel(LogLevel.Information)) // Debug is disabled
.CreateLogger("Bench");
[Benchmark(Baseline = true)]
public void ExtensionMethod() => _logger.LogDebug("Item {Id} took {Ms} ms", 42, 3.5);
[Benchmark]
public void Generated() => ItemProcessed(_logger, 42, 3.5);
[LoggerMessage(EventId = 1, Level = LogLevel.Debug, Message = "Item {Id} took {Ms} ms")]
private static partial void ItemProcessed(ILogger logger, int id, double ms);
}
LogDebug(...) call is free. Why it is wrong: The params array and boxing happen before the level check. Instead: Use [LoggerMessage] on hot paths.IsEnabled.if (logger.IsEnabled(...)). Why it is wrong: Noise for no gain; the generated methods already check. Instead: Guard only when building an argument is expensive.EventId for different events. Why it is wrong: Event ids are meant to identify an event type for querying and alerting. Instead: Keep ids unique, ideally in one catalogue class per area.Exception parameter; the generator passes it as the exception.dotnet-trace or count allocations with BenchmarkDotNet first.Generated logging pays twice: performance on hot paths and correctness at compile time. The second matters more in a big codebase, because a catalogue of [LoggerMessage] methods becomes the documented list of events your dashboards and alerts depend on. I don't mandate it everywhere; I enable CA1848 for libraries and request-path code, and leave start-up and rare paths on plain calls.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
[LoggerMessage] |
Hot paths, libraries, event catalogue | A method per event | Rare or temporary messages |
| Extension methods | Most low-volume code | Allocations per call | Loops at high throughput |
IsEnabled guard |
Expensive argument construction | Extra branch and nesting | Cheap arguments |
[LogProperties] |
Logging selected properties of an object | Extra package | Objects with personal data unless redacted |
A source generator is a compiler plug-in that reads your code (usually a marker attribute on a partial declaration) and adds new C# files to the compilation; it can never change or delete your code. .NET ships several: System.Text.Json ([JsonSerializable] on a JsonSerializerContext) for reflection-free serialisation, [GeneratedRegex] for regex compiled to C# at build time, [LoggerMessage] for allocation-free structured logging, [LibraryImport] for P/Invoke marshalling, and in ASP.NET Core the configuration binding and Request Delegate generators that replace reflection in Bind/Get<T> and minimal APIs. They improve startup, cut allocations and make code trim and Native AOT safe. Inspect output under Dependencies, Analyzers in the IDE, or set EmitCompilerGeneratedFiles to write the files to obj.
Boxing wraps a value type in a new heap object so it can be used as object or an interface; unboxing checks the object's type and copies the value back, and it must be the exact type or you get InvalidCastException. Every box is a heap allocation, so in hot paths it creates GC pressure. Hidden boxing comes from non-generic APIs like ArrayList and params object[], passing structs as interfaces, calling GetType() or non-overridden Equals/GetHashCode on structs, and enumerating a List<T> through IEnumerable<T>. I find it with BenchmarkDotNet's MemoryDiagnoser or an allocation profiler and fix it with generics, constraints and IEquatable<T>.
Structured logging records an event: a constant message template plus named properties, instead of a pre-built string. In logger.LogInformation("Order {OrderId} placed in {ElapsedMs} ms", id, ms), the provider gets the template and the values separately, so OrderId and ElapsedMs become queryable fields (Application Insights customDimensions, OpenTelemetry attributes, Seq properties).
With string interpolation ($"Order {id} placed") the provider only sees a finished string: no properties, a different message every time, and the string is built even when the level is disabled. Analyser CA2254 warns about this.
The trade-off: templates take discipline in naming, but they turn logs from text you grep into data you can filter, group and alert on.
How to tell it (STAR)
**S:** At [company] our order worker processed around [8,000] messages a second, and after a release p99 latency rose by about [60%] even though nothing functional had changed. **T:** I needed to find the regression quickly without rolling back the features in that release. **A:** I captured an allocation trace with dotnet-trace and saw boxed integers and object arrays from Debug log calls in the per-line loop dominating, even though Debug was disabled. I hotfixed the loop, then moved the worker to a `[LoggerMessage]` catalogue, guarded the one expensive argument, and added CA1848 plus an allocation benchmark to CI. **R:** Allocation rate dropped by [about 1.4 GB/s], p99 went back under [40] ms, and the analyser has since caught [several] similar calls in review.
Last updated 23 Nov 2026.