.NET 6中間件Http Logging使用介紹

Intro

.NET 6 會引入一個 Http logging 的中間件,可以用來幫助我們比較方便記錄請求和響應的信息

Sample

廢話不多說,直接來看示例吧

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
var app = builder.Build();

app.UseHttpLogging();
app.MapControllers();

app.Run();

dotnet run 運行起來項目,然後訪問一個接口就可以看到打印出來的 Http logging 的日志瞭

info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[1]
      Request:
      Protocol: HTTP/1.1
      Method: GET
      Scheme: http
      PathBase:
      Path: /weatherforecast
      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
      Connection: keep-alive
      Host: localhost:5084
      User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36
      Accept-Encoding: gzip, deflate, br
      Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7
      Cache-Control: [Redacted]
      Upgrade-Insecure-Requests: [Redacted]
      sec-ch-ua: [Redacted]
      sec-ch-ua-mobile: [Redacted]
      sec-ch-ua-platform: [Redacted]
      Sec-Fetch-Site: [Redacted]
      Sec-Fetch-Mode: [Redacted]
      Sec-Fetch-User: [Redacted]
      Sec-Fetch-Dest: [Redacted]
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[2]
      Response:
      StatusCode: 200
      Content-Type: application/json; charset=utf-8
      Date: [Redacted]
      Server: [Redacted]
      Transfer-Encoding: chunked

默認地,HttpLoggingMiddleware 會記錄請求的基本信息(請求地址,協議版本)和請求頭信息以及響應狀態和響應頭信息,對於不在默認列表裡的請求頭和響應頭,值會顯示為 [Redacted],如果需要記錄這個請求頭/響應頭的值則需要配置 HttpLoggingOptions,可以在註冊服務的時候進行配置,配置示例如下:

builder.Services.AddHttpLogging(options =>
{
    options.RequestHeaders.Add("Cache-Control");
    options.ResponseHeaders.Add("Server");
});

修改之後,重新啟動並請求我們的服務,日志輸出如下:

info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[1]
      Request:
      Protocol: HTTP/1.1
      Method: GET
      Scheme: http
      PathBase:
      Path: /weatherforecast
      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
      Connection: keep-alive
      Host: localhost:5084
      User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36
      Accept-Encoding: gzip, deflate, br
      Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7
      Cache-Control: max-age=0
      Upgrade-Insecure-Requests: [Redacted]
      sec-ch-ua: [Redacted]
      sec-ch-ua-mobile: [Redacted]
      sec-ch-ua-platform: [Redacted]
      Sec-Fetch-Site: [Redacted]
      Sec-Fetch-Mode: [Redacted]
      Sec-Fetch-User: [Redacted]
      Sec-Fetch-Dest: [Redacted]
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[2]
      Response:
      StatusCode: 200
      Content-Type: application/json; charset=utf-8
      Date: [Redacted]
      Server: Kestrel
      Transfer-Encoding: chunked

註意看一下請求頭裡的 Cache-Control 和響應頭裡的 Server,原來都是 [Redacted],配置之後就顯示正確的值瞭,如果你要記錄自定義的請求頭信息,也是類似的配置

接著我們來配置一下記錄請求信息和響應信息,可以配置 HttpLoggingOptions 中的 LoggingFields 來指定需要記錄哪些信息

builder.Services.AddHttpLogging(options =>
{
    options.LoggingFields = Microsoft.AspNetCore.HttpLogging.HttpLoggingFields.All;
    options.RequestHeaders.Add("Cache-Control");
    options.ResponseHeaders.Add("Server");
});

在上面的基礎上增加 LoggingFields 的配置,這裡直接配置上所有的信息,此時再來重新請求,查看日志如下:

info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[1]
      Request:
      Protocol: HTTP/1.1
      Method: GET
      Scheme: http
      PathBase:
      Path: /weatherforecast
      Host: localhost:5084
      User-Agent: dotnet-HTTPie/0.1.1
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[2]
      Response:
      StatusCode: 200
      Content-Type: application/json; charset=utf-8
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[4]
      ResponseBody: [{"date":"2021-09-25T23:40:11.0164783+08:00","temperatureC":37,"temperatureF":98,"summary":"Cool"},{"date":"2021-09-26T23:40:11.0164836+08:00","temperatureC":50,"temperatureF":121,"summary":"Warm"},{"date":"2021-09-27T23:40:11.0164838+08:00","temperatureC":-7,"temperatureF":20,"summary":"Scorching"},{"date":"2021-09-28T23:40:11.016484+08:00","temperatureC":39,"temperatureF":102,"summary":"Freezing"},{"date":"2021-09-29T23:40:11.0164842+08:00","temperatureC":4,"temperatureF":39,"summary":"Balmy"}]

可以看到此時的 response body 也記錄下來瞭

我們再來增加一個 POST 的 API 來驗證一下 RequestBody 是不是可以正常記錄

[HttpPost]
public IActionResult Post(System.Text.Json.JsonElement element) => Ok(element);

使用 dotnet-httpie 執行 http :5084/weatherforecast name=test

請求一下 API,輸出日志如下:

info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[1]
      Request:
      Protocol: HTTP/1.1
      Method: POST
      Scheme: http
      PathBase:
      Path: /weatherforecast
      Host: localhost:5084
      User-Agent: dotnet-HTTPie/0.1.1
      Content-Type: application/json; charset=utf-8
      Content-Length: 15
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[3]
      RequestBody: {"name":"test"}
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[2]
      Response:
      StatusCode: 200
      Content-Type: application/json; charset=utf-8
info: Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[4]
      ResponseBody: {"name":"test"}

More

仔細看上面的示例的話會發現一個問題,當要記錄 ResponseBody 的時候,Response header 的信息沒有被完全記錄下來,感覺像是一個 BUG,提瞭一個 issue 還沒回復,感興趣的可以參考:<https://github.com/dotnet/aspnetcore/issues/36920>

另外感覺這個中間件的日志級別都是 Information 級別的,如果可以根據響應狀態來動態配置日志級別就好瞭,比如說響應狀態碼大於等於 500 的時候,日志級別記錄為 ERROR, 這樣就可以有效地去除很多不必要的日志瞭,提瞭一個簡陋的 PR,有興趣的可以參考:https://github.com/dotnet/aspnetcore/pull/36873

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: