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