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:

Terminal window
dotnet new console -n LoggerMessageDemo -f net10.0
cd LoggerMessageDemo
dotnet add package Microsoft.Extensions.Logging.Console

Replace 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:

Terminal window
dotnet run

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