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 theLoggerMessagepattern.
LoggerMessageprovides the following performance advantages over Logger extension methods:
- Logger extension methods require "boxing" (converting) value types, such as
int, intoobject. TheLoggerMessagepattern avoids boxing by using staticActionfields 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.
LoggerMessageonly 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
Actiondelegate 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