A Roslyn analyzer that detects ILogger.Log* method calls and provides code fixes to convert them to compile-time generated logging using the [LoggerMessage] attribute for better performance.
The [LoggerMessage] attribute (introduced in .NET 6) enables source generation for high-performance logging:
- Zero allocations - No boxing of value types
- No parsing at runtime - Message templates are parsed at compile time
- Strongly typed - Compile-time validation of log message parameters
- Better performance - Up to 6x faster than traditional logging extensions
dotnet add package CompileTimeLoggerOr via Package Manager:
Install-Package CompileTimeLoggerThe analyzer detects calls like:
_logger.LogInformation("User {UserId} logged in", userId);And offers two code fixes:
// Before
_logger.LogInformation("User {UserId} logged in", userId);
// After
LogUserLoggedIn(userId);
[LoggerMessage(Level = LogLevel.Information, Message = "User {UserId} logged in")]
private partial void LogUserLoggedIn(string userId);// Before
_logger.LogInformation("User {UserId} logged in", userId);
// After
Log.UserLoggedIn(_logger, userId);
private static partial class Log
{
[LoggerMessage(Level = LogLevel.Information, Message = "User {UserId} logged in")]
public static partial void UserLoggedIn(ILogger logger, string userId);
}LogTraceLogDebugLogInformationLogWarningLogErrorLogCritical
- Works with both
ILoggerandILogger<T> - Handles exceptions in log calls (e.g.,
_logger.LogError(ex, "message")) - Automatically extracts message template placeholders
- Generates properly named methods from message templates
- Makes containing class
partialautomatically
- .NET 6.0 or later (for
[LoggerMessage]attribute support) - C# 9.0 or later
| ID | Description |
|---|---|
| CTL001 | ILogger.Log* call can be converted to compile-time generated logging |
MIT License - see LICENSE.txt