Improve logging performance with code generation
Avvalgi postda logging levels __(logging darajalari)__ni tushintirib bergan edim. Bugun logging tezligini oshirish uchun taklif etilayotgan yangi feature Logging Code Generation haqida gaplashamiz.
Code generation bu yangilik emas. Avvaldan Blazor, Razor va shunga o'xshash engine'lar compile vaqtida kod generate qiladi. .NET 6
versiyasida olib kirilgan yangi attribute LoggingMessageAttribute
bo'lsa aynan Logging samaradorligini oshirish uchun compile vaqtida reusable logging funksiyalari yaratish uchun ishlatiladi.
Ushbu qo'shimcha haqida batafsil bu yerda o'qishingiz mumkin.
Logging Code generation ishlatish uchun static partial
klas yaratib uni ichida partial
kalit so'zi orqali methodlar elon qilishingiz kerak. Bu methodlarni tanasi compile vaqtida .NET tomonidan yaratiladi va qayta ishlatiladi.
public static partial class ValidationFilterLoggings
{
[LoggerMessage(
EventId = 0,
Level = LogLevel.Trace,
Message = "Fluent validation started for type {targetType}.")]
public static partial void LogValidationStarted(
this ILogger logger,
string targetType);
}
E'lon qilingan funksiyani tanasi compile vaqtida .NET tomonidan yaratiladi.
Keyin ushbu logging methodni quyidagicha ishlatsa bo'ladi.
public class AsyncFluentValidationFilter<T> : IEndpointFilter where T : class
{
private readonly ILogger<AsyncFluentValidationFilter<T>> logger;
public AsyncFluentValidationFilter(ILogger<AsyncFluentValidationFilter<T>> logger)
=> this.logger = logger;
public async ValueTask<object> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
...
logger.LogValidationStarted(nameof(T));
...
}
}
Note
Yuqorida elon qilingan LogValidationStarted
funksiyasi ILogger
interface ustiga qurilgani uchun, bu methodni istalgan ILogger
interface obyektida ishlatsa bo'ladi.
Agar sizga maxsus bitta generic ILogger<T>
ustida ishlaydigan mehod kerak bo'lsa, this ILogger<T>
shaklida elon qilishingiz kerak. Misol uchun quyidagi kodga qarang 👀
public static partial class ValidationFilterLoggings
{
[LoggerMessage(
EventId = 1,
Level = LogLevel.Trace,
Message = "Fluent validation for {targetType} is successful.")]
public static partial void LogValidationCompleted(
this ILogger<AsyncFluentValidationFilter<T>> logger,
string targetType);
}