Serilog.AspNetCore 使用紀錄
Serilog, WebAPI, ASP.NET Core
源由
Serilog.AspNetCore
是專為 Web API 組織的,把需要的套件用相依關聯指定,功能基本延用已知只增加二項:
UseSerilogRequestLogging()
:為 Middleware,紀錄所有 Web Request 結果。EnrichDiagnosticContext
、IDiagnosticContext
:用來增加UseSerilogRequestLogging()
紀錄資訊。
參考文章 --- 看這篇就行了
開發環境
平台:.NET6
IDE: Visual Studio 2022
專案:Blazor WASM App.Server
關鍵源碼
using Microsoft.AspNetCore.ResponseCompression;
using Serilog;
using Serilog.Events;
/// 參考:[.NET 6.0 如何使用 Serilog 對應用程式事件進行結構化紀錄](https://blog.miniasp.com/post/2021/11/29/How-to-use-Serilog-with-NET-6)
/// 把 "Microsoft.AspNetCore" 預設為 Information 會倒出太細的資訊,故拉高到 Warning 降低紀錄筆數。
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("Starting web application");
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog(); //<--- Serilog
#region //§§ Add services to the container. -------------------------------------------
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
#endregion
var app = builder.Build();
#region //§§ Configure the HTTP request pipeline. -------------------------------------
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
///※ 格式化紀錄內容
///※ Serilog.AspNetCore 的精華在此段
app.UseSerilogRequestLogging(options =>
{
// Customize the message template。輸出紀錄內容在此
options.MessageTemplate = "Handled {UserID} => {RequestScheme} {RequestHost} {RequestPath} {RequestContentType} => {ResponseStatus} {ResponseContentType} ";
//// Emit debug-level events instead of the defaults
//options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Debug;
// Attach additional properties to the request completion event
// ※ 將可用在『MessageTemplate』輸出紀錄內容。
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
diagnosticContext.Set("UserID", httpContext.User.Identity?.Name ?? "guest");
diagnosticContext.Set("RequestContentType", httpContext.Request.ContentType);
diagnosticContext.Set("ResponseStatus", httpContext.Response.StatusCode);
diagnosticContext.Set("ResponseContentType", httpContext.Response.ContentType);
};
});
app.UseRouting();
#endregion
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
沒圖沒真象

(EOF)
PreviousAddController vs AddMvc vs AddControllersWithViews vs AddRazorPagesNextBlazor WASM App 實作多國語系紀錄
Last updated