You have a log statement inside a loop that runs thousands of times. The message is useful, but building it over and over can mean extra work and extra garbage for the collector.
The logging source generator can build that method for you at compile time.
Try It
Create a .NET 10 console app and add the console logger:
dotnet new console -n LoggerMessageDemo -f net10.0cd LoggerMessageDemodotnet add package Microsoft.Extensions.Logging.ConsoleReplace Program.cs with this:
using Microsoft.Extensions.Logging;
using var loggerFactory = LoggerFactory.Create(builder => builder.AddSimpleConsole());
ILogger logger = loggerFactory.CreateLogger("Worker");
for (var item = 1; item <= 3; item++){ Log.ProcessedItem(logger, item);}
public static partial class Log{ [LoggerMessage( EventId = 1, Level = LogLevel.Information, Message = "Processed item {ItemNumber}")] public static partial void ProcessedItem( ILogger logger, int itemNumber);}Run it:
dotnet runThe generator supplies the body of ProcessedItem during the build. You call it like an ordinary method, and the log message keeps its structured ItemNumber field.
What’s the Catch?
The containing type and method need to be partial. The message template is fixed at compile time, so use regular logging when the message itself needs to be dynamic.
This is most useful for hot paths or logs you call often. For a one off startup message, plain logger.LogInformation is perfectly fine.
Key Takeaway
[LoggerMessage] gives you compile time generated logging code without giving up structured logs. Start with the log statements that run a lot. No need to turn every log into a ceremony.