Logging is an essential part of modern .NET application development. It helps developers understand application behavior, investigate production issues, monitor background services, and identify failures. However, logging also introduces runtime overhead. In applications that process thousands of requests or background operations, unnecessary allocations and repeated message formatting can affect performance.
Consider an ASP.NET Core API that processes thousands of requests every second. If every request writes multiple log messages using traditional logging extension methods, the application may spend additional CPU time parsing message templates, creating temporary objects, and boxing value types. These operations may happen even when the configured log level prevents the message from being written.
.NET provides source-generated logging through the LoggerMessageAttribute. Instead of relying on runtime message-template processing, the compiler generates strongly typed logging methods during compilation. This reduces unnecessary allocations and improves logging performance.
Source-generated logging has been available since .NET 6 and remains the recommended approach for high-performance logging in modern .NET applications, including .NET 10.
This article explains how source-generated logging works, how to implement it in ASP.NET Core and worker services, how to handle exceptions and dynamic log levels, and how to migrate existing logging code without changing the application's logging behavior.
Why Traditional Logging Can Affect Application Performance
.NET provides convenient logging extension methods such as LogInformation, LogWarning, LogError, and LogDebug.
A typical logging statement looks like this:
logger.LogInformation(
"Order {OrderId} was processed in {ElapsedMilliseconds} ms",
orderId,
elapsedMilliseconds);This syntax is easy to understand and works well for many applications. However, traditional logging extension methods can introduce additional runtime work.
Message template processing
The logging framework must interpret the message template and associate its placeholders with the supplied values.
For example:
logger.LogInformation(
"Customer {CustomerId} placed order {OrderId}",
customerId,
orderId);The framework needs to identify the CustomerId and OrderId properties and associate them with the corresponding arguments.
Traditional logging APIs perform message-template processing at runtime. Source-generated logging moves much of this work to compile time.
Boxing value types
Boxing happens when a value type is converted into an object.
For example, an integer passed through an object-based logging argument can require boxing:
int orderId = 1050;
logger.LogInformation(
"Order ID: {OrderId}",
orderId);The traditional logging extension methods use object-based argument handling. Value types such as int, long, and bool can therefore require boxing.
Source-generated logging uses strongly typed method parameters and avoids this unnecessary conversion in its optimized implementation.
Temporary memory allocations
Logging operations can create temporary objects and allocations. These allocations may appear small individually, but their cumulative impact can become noticeable in high-throughput applications.
For example, an API that processes a large number of requests may generate several log messages for each request. Even a small amount of additional allocation per message can increase garbage collection activity over time.
Source-generated logging reduces these allocations by generating optimized logging implementations.
What Is Source-Generated Logging in .NET?
Source-generated logging uses C# source generators to create logging method implementations during compilation.
The main component is LoggerMessageAttribute, available in the Microsoft.Extensions.Logging namespace.
Instead of directly calling LogInformation or LogError, developers declare partial methods and decorate them with the LoggerMessage attribute.
The source generator examines these declarations and creates the method implementations.
The generated code uses the ILogger infrastructure while avoiding much of the repeated runtime work associated with traditional logging extension methods.
The main benefits include:
Reduced boxing of value types.
Fewer temporary memory allocations.
Message templates processed at compile time.
Strongly typed logging parameters.
Compile-time diagnostics for invalid logging declarations.
Centralized event IDs, log levels, and message templates.
The generated implementation becomes part of the compiled assembly. You can inspect it during development to understand how the logging method is implemented.
Implement Source-Generated Logging
Let's create a practical example using an order-processing application.
Assume an application processes customer orders and needs to log successful processing, validation failures, and unexpected exceptions.
Create a logging class
Create a file named OrderLogMessages.cs.
using Microsoft.Extensions.Logging;
namespace OrderProcessing.Logging;
public static partial class OrderLogMessages
{
[LoggerMessage(
EventId = 1001,
Level = LogLevel.Information,
Message = "Order {OrderId} was processed successfully.")]
public static partial void OrderProcessed(
ILogger logger,
int orderId);
[LoggerMessage(
EventId = 1002,
Level = LogLevel.Warning,
Message = "Order {OrderId} failed validation.")]
public static partial void OrderValidationFailed(
ILogger logger,
int orderId);
[LoggerMessage(
EventId = 1003,
Level = LogLevel.Error,
Message = "Failed to process order {OrderId}.")]
public static partial void OrderProcessingFailed(
ILogger logger,
Exception exception,
int orderId);
}There are several important details in this implementation.
The class is declared as partial because the source generator adds the missing method implementations during compilation.
Each logging method is also declared as partial. The method signatures describe the information required by the logging operation, while the generator creates the implementation.
The EventId property assigns a stable numeric identifier to each event. Event IDs make it easier to identify and filter specific log events in monitoring systems.
The Level property defines the severity of the message. The available levels include Trace, Debug, Information, Warning, Error, and Critical.
The Message property defines the structured message template. Its placeholders should match the method parameters that represent log values.
The exception parameter is treated specially by the source generator. It is passed to the logging infrastructure as the exception associated with the event. You do not need to include an exception placeholder in the message template.
Call generated logging methods
Once the logging methods are declared, use them wherever the application needs to record events.
using Microsoft.Extensions.Logging;
using OrderProcessing.Logging;
public class OrderService
{
private readonly ILogger<OrderService> _logger;
public OrderService(ILogger<OrderService> logger)
{
_logger = logger;
}
public void ProcessOrder(int orderId)
{
try
{
// Perform order processing.
OrderLogMessages.OrderProcessed(
_logger,
orderId);
}
catch (ArgumentException)
{
OrderLogMessages.OrderValidationFailed(
_logger,
orderId);
throw;
}
catch (Exception ex)
{
OrderLogMessages.OrderProcessingFailed(
_logger,
ex,
orderId);
throw;
}
}
}The service no longer needs to repeat message templates or event IDs throughout its methods.
Instead, it calls strongly typed logging methods that describe the application events.
This approach also makes logging easier to maintain. If the message template or event ID needs to change, developers can update the centralized logging declaration rather than searching through multiple service classes.
Use Source-Generated Logging in ASP.NET Core
Source-generated logging works naturally with dependency injection in ASP.NET Core.
The framework already provides ILogger<T> through its dependency injection container. You can inject the logger into a service and use generated methods.
Consider an API endpoint that creates customer orders.
Create an API service
using Microsoft.Extensions.Logging;
public class CustomerOrderService
{
private readonly ILogger<CustomerOrderService> _logger;
public CustomerOrderService(
ILogger<CustomerOrderService> logger)
{
_logger = logger;
}
public async Task<bool> CreateOrderAsync(
int customerId,
int orderId)
{
try
{
await Task.Delay(100);
OrderLogs.OrderCreated(
_logger,
customerId,
orderId);
return true;
}
catch (Exception ex)
{
OrderLogs.OrderCreationFailed(
_logger,
ex,
customerId,
orderId);
return false;
}
}
}
internal static partial class OrderLogs
{
[LoggerMessage(
EventId = 2001,
Level = LogLevel.Information,
Message = "Customer {CustomerId} created order {OrderId}.")]
internal static partial void OrderCreated(
ILogger logger,
int customerId,
int orderId);
[LoggerMessage(
EventId = 2002,
Level = LogLevel.Error,
Message = "Order creation failed for customer {CustomerId}, order {OrderId}.")]
internal static partial void OrderCreationFailed(
ILogger logger,
Exception exception,
int customerId,
int orderId);
}The logging methods are declared in a separate partial class. This keeps the service focused on business operations while the logging declarations remain centralized.
In a production application, the service should normally handle only exceptions it can meaningfully recover from. Avoid catching every exception and returning a successful HTTP response when the operation has actually failed.
Register the service
In Program.cs, register the service through dependency injection:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<CustomerOrderService>();
var app = builder.Build();
app.MapPost(
"/orders/{customerId:int}/{orderId:int}",
async (
int customerId,
int orderId,
CustomerOrderService service) =>
{
var result = await service.CreateOrderAsync(
customerId,
orderId);
return result
? Results.Ok("Order created")
: Results.Problem("Order creation failed");
});
app.Run();ASP.NET Core supplies the logger automatically. There is no need to create an ILoggerFactory manually for every service.
This approach is useful for APIs, background services, message consumers, and other applications that use the .NET hosting infrastructure.
Use Dynamic Log Levels
In some applications, the log level depends on runtime conditions.
For example, a system may log an operation as Information during normal execution but use Warning when processing takes longer than an expected threshold.
Source-generated logging supports dynamic log levels by omitting the Level property from the attribute and accepting LogLevel as a method parameter.
Join the conversation! Your thoughts help the community grow.