Convert existing logging calls to use the LoggerMessage source generator for AOT-compatible logging with no boxing overhead and compile-time template parsing.
When to Use
- Optimizing logging performance in hot paths
- Preparing for Native AOT deployment
- Organizing scattered log messages into logical groupings
- Standardizing EventIds across the codebase
Steps
Find ILogger usages and logging calls
- Search for
ILogger field/parameter declarations
- Find all logging calls:
LogInformation, LogWarning, LogError, LogDebug, LogTrace, LogCritical
- Note the log message templates and parameters
Organize into logical groupings by domain
- Group related log messages by their functional area, eg:
LoggingValidationExtensions - validation-related logs
LoggingAuthenticationExtensions - auth-related logs
LoggingDatabaseExtensions - database-related logs
LoggingHttpExtensions - HTTP-related logs
LoggingCacheExtensions - caching-related logs
LoggingMessagingExtensions - messaging/queue-related logs
Create partial static classes with extension methods
public static partial class LoggingValidationExtensions
{
[LoggerMessage(
EventId = 1001,
Level = LogLevel.Warning,
Message = "Validation failed for {EntityType}: {Errors}")]
public static partial void ValidationFailed(
this ILogger logger, string entityType, string errors);
}
Use EventId ranges per category
- 1000-1999: Validation
- 2000-2999: Authentication
- 3000-3999: Database
- 4000-4999: HTTP
- 5000-5999: Cache
- 6000-6999: Messaging
- 7000-7999: General/Application
Replace inline logging calls with extension method calls
- Before:
_logger.LogWarning("Validation failed for {entityType}: {errors}", type, errs)
- After:
_logger.ValidationFailed(type, errs)
Verify with build
dotnet build
If build fails, review errors:
- Missing
using statements for the extension class namespace
- Parameter type mismatches
- Duplicate EventIds
Report results:
- List all created extension classes
- Show count of converted log messages per category
- Confirm build status
Key Notes
- Requires .NET 6+ - the source generator is built into the SDK
- Avoids boxing - value types are not boxed when passed to the generated methods
- Template parsed once - message template is parsed at compile time, not runtime
- Use PascalCase for placeholders -
{EntityType} not {entityType} (matching is case-insensitive, but PascalCase is the recommended convention)
- Extension methods - allows fluent
logger.MethodName() syntax
- Partial classes - required for source generator to emit the implementation
Example Conversion
Before:
_logger.LogInformation("User {UserId} logged in from {IpAddress}", userId, ip);
_logger.LogWarning("Failed login attempt for {Username}", username);
After:
// In LoggingAuthenticationExtensions.cs
public static partial class LoggingAuthenticationExtensions
{
[LoggerMessage(
EventId = 2001,
Level = LogLevel.Information,
Message = "User {UserId} logged in from {IpAddress}")]
public static partial void UserLoggedIn(
this ILogger logger, string userId, string ipAddress);
[LoggerMessage(
EventId = 2002,
Level = LogLevel.Warning,
Message = "Failed login attempt for {Username}")]
public static partial void FailedLoginAttempt(
this ILogger logger, string username);
}
// Usage
_logger.UserLoggedIn(userId, ip);
_logger.FailedLoginAttempt(username);
1---2name: dotnet-source-gen-logging3description: Converts logging to use the LoggerMessage source generator for high-performance, AOT-compatible logging. Also use when the user mentions "LoggerMessage," "logging source generator," "high-performance logging," "optimize logging," "AOT logging," or "structured logging source gen." For full AOT analysis, see dotnet-aot-analysis.4license: MIT5metadata:6 source: https://skillmd.com/skills/im5tu-claude/dotnet-source-gen-logging7 author: Im5tu8 version: "1.0"9 repositoryUrl: https://github.com/im5tu/dotnet-skills10allowed-tools: Bash(dotnet:*), Read, Edit, Write, Glob, Grep, AskUserQuestion11---1213Convert existing logging calls to use the `LoggerMessage` source generator for AOT-compatible logging with no boxing overhead and compile-time template parsing.1415## When to Use1617- Optimizing logging performance in hot paths18- Preparing for Native AOT deployment19- Organizing scattered log messages into logical groupings20- Standardizing EventIds across the codebase2122## Steps23241. **Find ILogger usages and logging calls**25 - Search for `ILogger` field/parameter declarations26 - Find all logging calls: `LogInformation`, `LogWarning`, `LogError`, `LogDebug`, `LogTrace`, `LogCritical`27 - Note the log message templates and parameters28292. **Organize into logical groupings by domain**30 - Group related log messages by their functional area, eg:31 - `LoggingValidationExtensions` - validation-related logs32 - `LoggingAuthenticationExtensions` - auth-related logs33 - `LoggingDatabaseExtensions` - database-related logs34 - `LoggingHttpExtensions` - HTTP-related logs35 - `LoggingCacheExtensions` - caching-related logs36 - `LoggingMessagingExtensions` - messaging/queue-related logs37383. **Create partial static classes with extension methods**39 ```csharp40 public static partial class LoggingValidationExtensions41 {42 [LoggerMessage(43 EventId = 1001,44 Level = LogLevel.Warning,45 Message = "Validation failed for {EntityType}: {Errors}")]46 public static partial void ValidationFailed(47 this ILogger logger, string entityType, string errors);48 }49 ```50514. **Use EventId ranges per category**52 - 1000-1999: Validation53 - 2000-2999: Authentication54 - 3000-3999: Database55 - 4000-4999: HTTP56 - 5000-5999: Cache57 - 6000-6999: Messaging58 - 7000-7999: General/Application59605. **Replace inline logging calls with extension method calls**61 - Before: `_logger.LogWarning("Validation failed for {entityType}: {errors}", type, errs)`62 - After: `_logger.ValidationFailed(type, errs)`63646. **Verify with build**65 ```bash66 dotnet build67 ```68697. **If build fails**, review errors:70 - Missing `using` statements for the extension class namespace71 - Parameter type mismatches72 - Duplicate EventIds73748. **Report results**:75 - List all created extension classes76 - Show count of converted log messages per category77 - Confirm build status7879## Key Notes8081- **Requires .NET 6+** - the source generator is built into the SDK82- **Avoids boxing** - value types are not boxed when passed to the generated methods83- **Template parsed once** - message template is parsed at compile time, not runtime84- **Use PascalCase for placeholders** - `{EntityType}` not `{entityType}` (matching is case-insensitive, but PascalCase is the recommended convention)85- **Extension methods** - allows fluent `logger.MethodName()` syntax86- **Partial classes** - required for source generator to emit the implementation8788## Example Conversion8990Before:91```csharp92_logger.LogInformation("User {UserId} logged in from {IpAddress}", userId, ip);93_logger.LogWarning("Failed login attempt for {Username}", username);94```9596After:97```csharp98// In LoggingAuthenticationExtensions.cs99public static partial class LoggingAuthenticationExtensions100{101 [LoggerMessage(102 EventId = 2001,103 Level = LogLevel.Information,104 Message = "User {UserId} logged in from {IpAddress}")]105 public static partial void UserLoggedIn(106 this ILogger logger, string userId, string ipAddress);107108 [LoggerMessage(109 EventId = 2002,110 Level = LogLevel.Warning,111 Message = "Failed login attempt for {Username}")]112 public static partial void FailedLoginAttempt(113 this ILogger logger, string username);114}115116// Usage117_logger.UserLoggedIn(userId, ip);118_logger.FailedLoginAttempt(username);119```