1. 程式人生 > 程式設計 >.NET 6中介軟體Http Logging使用介紹

.NET 6中介軟體Http Logging使用介紹

Intro

.NET 6 會引入一個 Http logging 的中介軟體,可以用來幫助我們比較方便記錄請求和響應的資訊

Sample

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

varbuilder=WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
varapp=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(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/94.0.4606.54Safari/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.HttpLoggingMiwww.cppcns.com
ddleware[2] Response: StatusCode:200 Content-Type:application/on;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,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]
publicIActionResultPost(System.Text.Json.JsonElementelement)=>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/jMLDlpqZson;charset=utf-8
info:Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware[4]
ResponseBody:{"name":"test"}

More

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

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。