Bổ sung thông tin vào HTTP request logs trong ASP.NET Core
Bạn có thể tạo HTTP log enricher (bộ bổ sung thông tin nhật ký HTTP) tùy chỉnh bằng cách tạo class implement interface IHttpLogEnricher. Khác với general-purpose log enrichers (bộ bổ sung log đa dụng) làm giàu tất cả logs trong ứng dụng, HTTP log enrichers chỉ nhắm vào incoming HTTP request logs trong ASP.NET Core, cho phép bạn thêm thông tin ngữ cảnh dựa trên HttpContext của mỗi request.
Sau khi tạo class, bạn đăng ký nó với AddHttpLogEnricher<T>(IServiceCollection). Khi đã đăng ký, logging infrastructure tự động gọi phương thức Enrich() trên mỗi enricher đã đăng ký cho từng HTTP request đến được xử lý bởi ASP.NET Core pipeline.
Interface IHttpLogEnricher là experimental (thử nghiệm) và yêu cầu suppress diagnostic ID EXTEXP0013.
Cài đặt package
Để bắt đầu, cài đặt NuGet package Microsoft.AspNetCore.Diagnostics.Middleware:
dotnet add package Microsoft.AspNetCore.Diagnostics.Middleware
Hoặc nếu dùng .NET 10+ SDK:
dotnet package add Microsoft.AspNetCore.Diagnostics.Middleware
Hoặc qua PackageReference:
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.Middleware"
Version="*" />Implementation IHttpLogEnricher
HTTP log enricher tùy chỉnh cần implement một phương thức duy nhất Enrich(IEnrichmentTagCollector, HttpContext). Trong quá trình enrichment (bổ sung thông tin), phương thức này được gọi và được trao instance IEnrichmentTagCollector cùng với HttpContext cho request đến. Enricher sau đó gọi một trong các overload của phương thức Add(String, Object) để ghi lại các thuộc tính muốn lưu.
Nếu HTTP log enricher tùy chỉnh gọi Add(String, Object), có thể truyền bất kỳ kiểu đối số nào vào tham số value, vì nó sẽ được parse thành kiểu thực và serialize nội bộ để gửi tiếp qua logging pipeline.
using Microsoft.AspNetCore.Diagnostics.Logging;
using Microsoft.Extensions.Diagnostics.Enrichment;
public class CustomHttpLogEnricher : IHttpLogEnricher
{
public void Enrich(IEnrichmentTagCollector collector, HttpContext httpContext)
{
// Thêm custom tags dựa trên HTTP request đến
collector.Add("request_method", httpContext.Request.Method);
collector.Add("request_scheme", httpContext.Request.Scheme);
// Thêm tags dựa trên response status code (có sẵn trong phase response)
collector.Add("response_status_code", httpContext.Response.StatusCode);
// Thêm tags dựa trên trạng thái xác thực của user
if (httpContext.User?.Identity?.IsAuthenticated is true)
{
collector.Add("user_authenticated", true);
}
}
}Và đăng ký như sau bằng AddHttpLogEnricher<T>(IServiceCollection):
using System.Text.Json;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpLogEnricher<CustomHttpLogEnricher>();
builder.Services.AddRedaction();
builder.Logging.AddJsonConsole(op =>
{
op.JsonWriterOptions = new JsonWriterOptions
{
Indented = true
};
});
WebApplication app = builder.Build();
app.UseHttpLogging();
app.MapGet("/", () => "Hello, World!");
await app.RunAsync();Điểm khác biệt chính so với general log enrichers
HTTP log enrichers khác với general-purpose log enrichers (ILogEnricher) ở nhiều điểm quan trọng:
- Phạm vi (Scope): HTTP log enrichers chỉ làm giàu logs được tạo ra bởi incoming ASP.NET Core HTTP requests, trong khi general log enrichers làm giàu tất cả logs trong ứng dụng.
- Context (ngữ cảnh): HTTP log enrichers có quyền truy cập vào toàn bộ
HttpContext, bao gồm request, response, user, connection và bất kỳ dữ liệu ngữ cảnh nào liên quan đến request đến. - Package: HTTP log enrichers yêu cầu package
Microsoft.AspNetCore.Diagnostics.Middleware, trong khi general log enrichers dùng packageMicrosoft.Extensions.Telemetry.Abstractions. - Hướng (Direction): HTTP log enrichers nhắm vào incoming (đến) server-side requests, trong khi IHttpClientLogEnricher nhắm vào outgoing (đi) client-side HTTP requests.
Ghi chú
- Phương thức
Enrichđược gọi trong phase HTTP response của vòng đời request/response, sau khi response đã được xử lý. - Tham số
httpContextluôn được cung cấp và không bao giờ lànull. - Có thể đăng ký nhiều enrichers và chúng sẽ được thực thi theo thứ tự đăng ký.
- Nếu một enricher ném exception, exception đó sẽ được ghi lại và việc thực thi tiếp tục với các enrichers còn lại.
- Interface
IHttpLogEnricherđược đánh dấu là experimental với diagnostic IDEXTEXP0013và yêu cầu .NET 8 trở lên. - Gọi
AddHttpLogEnricher<T>()tự động thiết lập HTTP logging redaction infrastructure bằng cách gọiAddHttpLoggingRedaction()nội bộ. - Bạn vẫn phải thêm middleware
UseHttpLogging()vào application pipeline để HTTP logs được phát ra.