One of the hidden features of ASP.NET Core is the support for LoggerMessage.
From the documentation:
LoggerMessage features create cacheable delegates that require fewer object allocations and reduced computational overhead compared to logger extension methods, such as
LogInformation
,LogDebug
, andLogError
. For high-performance logging scenarios, use theLoggerMessage
pattern.
LoggerMessage
provides the following performance advantages over Logger extension methods:
- Logger extension methods require "boxing" (converting) value types, such as
int
, intoobject
. TheLoggerMessage
pattern avoids boxing by using staticAction
fields and extension methods with strongly-typed parameters.- Logger extension methods must parse the message template (named format string) every time a log message is written.
LoggerMessage
only requires parsing a template once when the message is defined.
The best way to use it is through some extension methods on the ILogger interface:
- Create a static LoggerExtensions class
- Add a static constructor and use the Define(LogLevel, EventId, String) method to create an
Action
delegate for logging a message. For theAction
, specify: - The log level.
- A unique event identifier (EventId) with the name of the static extension method.
- The message template (named format string).
- Store the created Action delegate in a private static field
- Create an extension method that invokes the delegate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class LoggerExtensions | |
{ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static LoggerExtensions() | |
{ | |
_indexPageRequested = LoggerMessage.Define( | |
LogLevel.Information, | |
new EventId(1, nameof(IndexPageRequested)), | |
"GET request for Index page"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static readonly Action<ILogger, Exception> _indexPageRequested; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void IndexPageRequested(this ILogger logger) | |
{ | |
_indexPageRequested(logger, null); | |
} |