Nguon: Microsoft Learn · .NET 8.0

Bổ sung thông tin vào HTTP request logs trong ASP.NET Core

Nguồn: Enrich HTTP request logs in 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:

dotnetcli
dotnet add package Microsoft.AspNetCore.Diagnostics.Middleware

Hoặc nếu dùng .NET 10+ SDK:

dotnetcli
dotnet package add Microsoft.AspNetCore.Diagnostics.Middleware

Hoặc qua PackageReference:

xml
<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.

csharp
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&lt;T&gt;(IServiceCollection):

csharp
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:

Ghi chú