If you mention logging in
.NET, you will definitely think of ILogger, which is a common way to provide logging in
.NET. The following code is the code for the initialization of the .NET Core WebAPI project, which uses ILogger to provide logging Logging.
NET6 Microsoft provides us with a high-performance logging class LoggerMessage. Compared to the ILogger logger and its extension methods, LoggerMessage has performance advantages. First, the ILogger logger extension methods require value type conversion to object, but LoggerMessage uses static methods with strongly typed parameters and extension methods to avoid this problem. Also, the ILogger logger and its extension methods must first parse the message template each time the log is written, but LoggerMessage only needs to parse the template once if the message template is already defined. The code used is as follows (modifying the WebAPI project initialization code)
Although LoggerMessage provides us with better performance logging, it requires a lot of manual writing of LoggerMessage.Define code, and the parameter placeholders in the formatString message template are not controlled in any way, which may lead to incorrect passing of parameters. NET 6 Microsoft provides Source Generator to help us automatically generate high-performance logging code. It is very simple to use, first you need to create partial method and second declare LoggerMessageAttribute attribute in the partial method header. The code used is as follows.
Once compiled, LoggerMessage automatically generates the code for us.
In the above code, the LogWeatherForecast method directly uses the
_logger object declared in the Controller without us passing it in, and also determines _logger.IsEnabled before writing logs, which avoids unnecessary log writing and further improves performance. While using LoggerMessageAttribute can improve logging performance, it also has its disadvantages.
- using partial method declarations requires that the class also be defined as partial. 2.Logging uses the ToString() method of the parameter object, and for complex types you cannot pass a serialized object into the method LogWeatherForecast(JsonSerializer.Serialize(result)) because it will always be executed and affect the performance, but you can define it as a record class or Custom ToString() method workaround.