If you can upgrade to dotnet core 6 you dont have to write your own request/response body logging middleware. Microsoft have one in the aspnet framework.
This can be setup to work with serilog, although i found the serilog documentation to be wrong in that the startup code needs both Microsofts UseHttpLogging and Serilogs UseSerilogRequestLogging (Serilog doco says just use theirs ... that didnt write the bodies)
Serilog documentation
Microsofts new aspnet dotnet 6 logging documentation
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app
.UseHttpsRedirection()
.UseRouting()
.UseHttpLogging()
.UseSerilogRequestLogging()
.UseSwagger()
.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Some.api"))
.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
To make this complete (as per the doco on the logging from microsoft) you can setup options such as
services.AddHttpLogging(logging =>
{
logging.LoggingFields = HttpLoggingFields.All;
logging.RequestHeaders.Add(HeaderNames.Accept);
logging.RequestHeaders.Add(HeaderNames.ContentType);
logging.RequestHeaders.Add(HeaderNames.ContentDisposition);
logging.RequestHeaders.Add(HeaderNames.ContentEncoding);
logging.RequestHeaders.Add(HeaderNames.ContentLength);
logging.MediaTypeOptions.AddText("application/json");
logging.MediaTypeOptions.AddText("multipart/form-data");
logging.RequestBodyLogLimit = 1024;
logging.ResponseBodyLogLimit = 1024;
});
And dont forget appsettings.json for microsoft logging and for serilog. Such as:
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Information",
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information"
}
},
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.AspNetCore": "Information",
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Information"
}
},
"WriteTo": [
{
"Name": "File",
"Args": { "path": "c:/data/logs/aspnetcore-log-.txt", "rollingInterval": "Day" }
}
]
},
And you need to call the UseSerilog extension, such as:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console())
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });