📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how you write high-performance logging in .NET. Use the [LoggerMessage] source generator, explain what it does differently from logger.LogInformation(...) with arguments, when IsEnabled checks still matter, and how you would prove the difference with a benchmark.

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.

Mid-Level Coding Intermediate aspnet-core benchmarkdotnet loggermessage logging performance source-generators

🎯 Key points

  • logger.LogInformation(template, args) allocates a params object[] and boxes value types on every call, even when the level is disabled
  • [LoggerMessage(EventId, Level, Message)] on a partial method generates a strongly typed method with a cached formatter and an IsEnabled check first
  • Generated code avoids the array and boxing on the disabled path, so a filtered call costs about a nanosecond and zero bytes
  • The generator validates at compile time that placeholders match parameters (diagnostics SYSLIB1xxx)
  • Works as static extension methods (ILogger parameter) or instance methods using an ILogger field or primary constructor parameter
  • IsEnabled still matters when computing an argument is expensive (serialising, LINQ) because arguments are evaluated before the call
  • CA1848 suggests LoggerMessage; enable it for libraries and hot paths
  • Measure with BenchmarkDotNet [MemoryDiagnoser] and dotnet-counters allocation rate, not guesswork

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The convenient extension methods hide some work. logger.LogDebug("Item {Id} took {Ms} ms", id, ms) compiles to a call with a params 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 a partial method with the attribute, giving the event id, level and template, and the generator writes the body at compile time: it calls IsEnabled first, 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 no orderId parameter, 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 in if (logger.IsEnabled(LogLevel.Debug)). And I prove all of this with BenchmarkDotNet and MemoryDiagnoser rather than by assumption. Generated logging is the cheapest correct default for hot paths."


What each approach costs

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 – –

When to use it

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

Production example

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%].

🔍 What the interviewer is checking

Checks whether the candidate knows the hidden cost of logging calls and the modern, compile-time solution, and measures before optimising.

Green flags

  • Explains the params array and boxing on the disabled path.
  • Writes a correct [LoggerMessage] partial method and knows what it generates.
  • Knows arguments are still evaluated and guards expensive ones.
  • Proposes BenchmarkDotNet with MemoryDiagnoser or dotnet-counters.

Red flags

  • Wraps every call in IsEnabled without understanding why.
  • Thinks string interpolation is fine because "the compiler optimises it".
  • Claims big savings without a measurement.

📚 Learn in depth

1. What the extension method compiles to

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.

2. What the generator writes

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.

3. Instance methods and primary constructors

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.

4. Arguments are still evaluated

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.

5. Compile-time diagnostics

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.

6. Indicative numbers

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.

Try it yourself

  1. Run the benchmark in the code example and compare Allocated columns.
  2. Remove a parameter from a [LoggerMessage] method and read the SYSLIB diagnostic.
  3. Press F12 on a generated method in Visual Studio or Rider and read the emitted code.
  4. Run a hot loop with both styles under dotnet-counters monitor -p <pid> System.Runtime and compare gc-heap-alloc-rate (or dotnet.gc.heap.total_allocated in .NET 9+).
  5. Turn on CA1848 as a warning and count how many calls in your service it flags.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: Assuming a disabled LogDebug(...) call is free. Why it is wrong: The params array and boxing happen before the level check. Instead: Use [LoggerMessage] on hot paths.
  • Mistake: Believing the generator skips argument evaluation. Why it is wrong: C# evaluates arguments before calling any method. Instead: Guard expensive arguments with IsEnabled.
  • Mistake: Wrapping every single log call in 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.
  • Mistake: Reusing the same 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.
  • Mistake: Passing the exception as a template placeholder. Why it is wrong: It is formatted as text and lost from the exception field. Instead: Declare an Exception parameter; the generator passes it as the exception.
  • Mistake: Optimising logging without measuring. Why it is wrong: In many apps logging is not the bottleneck. Instead: Profile with dotnet-trace or count allocations with BenchmarkDotNet first.
  • Mistake: Converting every log line in a one-off admin tool. Why it is wrong: Extra code with no measurable benefit. Instead: Reserve generated logging for hot paths and shared libraries.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the generator writes the method body at compile time. Why: Checks they understand how source generators work in general and how to inspect generated code.
    How to answer

    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.

  2. When: Candidate mentions boxing of value-type arguments in log calls. Why: Checks they can explain boxing and find it with tools.
    How to answer

    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>.

  3. When: Candidate mentions compile-time checking of placeholders. Why: Checks they connect generated methods to structured logging and consistent property names.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Debug logging that was 'off' still caused GC pressure in a queue consumer
Situation
A .NET worker on [AKS] processed about [8,000] Service Bus messages a second for [an order pipeline]. Throughput dropped after a release that added detailed Debug logging, even though production ran at Information.
Signals
p99 processing time up from [40] to [65] ms; dotnet-counters showed allocation rate up by [~1.4 GB/s] and Gen0 collections tripled; CPU up [10%] with no change in message volume.
Investigation
Collected an allocation trace with `dotnet-trace collect --profile gc-verbose` and opened it in PerfView: top allocating stacks were `object[]` and boxed `Int32`/`Double` from `LoggerExtensions.LogDebug` inside the per-line loop. Confirmed with a BenchmarkDotNet test that a disabled `LogDebug` with three value-type arguments allocated [~70] bytes.
Resolution
Immediate: removed the per-line Debug calls from the hot loop in a hotfix. Long term: moved the worker's events to a `[LoggerMessage]` catalogue and guarded one call that serialised the message body with `IsEnabled(LogLevel.Trace)`.
Prevention
Enabled CA1848 as a warning for the worker project; added a BenchmarkDotNet allocation test for the handler with a budget; added Gen0 collection rate to the service dashboard with an alert on regression.

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.

↩ Usually asked after

More in Logging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me