Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Fix a Source-Generated Logging Message That Still Evaluates Its Arguments Even When the Log Level Is Disabled

- 04.10.26 - ErcanOPAK

🔧 The Log Line That Ran Even When Nobody Was Listening

A source-generated logging method is supposed to skip the actual work of formatting a message entirely when its log level is disabled in configuration, which is the whole performance case for using it instead of a plain string interpolation. That guarantee covers the message template itself – it does not extend to whatever expression you pass in as an argument, because every argument is evaluated by the caller before the generated method is ever invoked. A seemingly innocent argument that calls a method, serializes an object, or walks a collection still runs in full on every single call, disabled log level or not, and the cost hides in code that looks like it should be free.

🔎 The Problem

public partial class OrderService
{
    [LoggerMessage(Level = LogLevel.Debug, Message = "Order snapshot: {Snapshot}")]
    partial void LogOrderSnapshot(string snapshot);

    public void Process(Order order)
    {
        // The generated method itself skips formatting when Debug
        // is disabled - but the argument expression right here is
        // evaluated by THIS line, before LogOrderSnapshot ever runs,
        // so SerializeFullSnapshot() executes on every single call
        // no matter what level is configured.
        LogOrderSnapshot(SerializeFullSnapshot(order));
    }

    string SerializeFullSnapshot(Order order)
    {
        // A full JSON serialization of a deep object graph - meant
        // to be a debug-only diagnostic, not something that runs on
        // every order in production with Debug logging turned off.
        return JsonSerializer.Serialize(order, DeepGraphOptions);
    }
}

✅ Fix: Keep Expensive Arguments Out of the Call Entirely

  • Guard an expensive argument expression with an explicit IsEnabled check before building it, so the serialization or formatting work only happens when the configured log level would actually use the result.
  • Pass the raw pieces the message template needs – an identifier, a count, a status – as separate structured arguments instead of pre-building one expensive composite string, letting the generated method’s own level check decide whether formatting ever happens.
  • Reserve a full object dump for a dedicated, clearly named diagnostic method gated by its own explicit check, rather than folding it into a routine log call that runs on every request regardless of the configured level.

⚠️ Why This Is Easy to Miss

  • The whole point of switching to source-generated logging is that the framework promises to skip unnecessary work, so it is easy to assume that promise covers everything inside the call, including the arguments, rather than just the formatting step after they arrive.
  • A local development environment usually runs with verbose logging enabled anyway, so the expensive argument runs there regardless of the guard – the actual waste only becomes visible once production runs with a quieter configured level.

A logging call that skips its own formatting still ran every argument you handed it first – the free log line was never free if what you passed it wasn’t.

— C# Best Practice

Related posts:

C#: Use init Accessors for Immutable Objects with Object Initializers

C#: Use init Accessors for Immutable Objects with Object Initializers

C#: Fix a Deconstruct Method Never Matching a Pattern Switch

C#: Fix a Deconstruct Method Never Matching a Pattern Switch

C#: Async/Await Best Practices for High-Performance Apps

C#: Async/Await Best Practices for High-Performance Apps

Views: 9
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Ajax: Fix a Fetch Call That Silently Ignores Your Abort Signal Because the Controller Was Created After the Request Already Started
Windows 11: Fix File Explorer Search That Returns Zero Results Even Though Indexing Shows as Complete

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,080 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 999 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 998 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 874 views
  5. 05How to select distinct rows in a datatable in C# 869 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 673 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 632 views
  8. 08Average of all values in a column that are not zero in SQL 586 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 563 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com