ASP.NET Core MVC and `UseSerilogRequestLogging()`

TL;DR: Use action filters and IDiagnosticContext to selectively add MVC handler information to your app’s request completion events.

This post is a follow-up from yesterday’s post about Serilog integration into ASP.NET Core 3 logging. It introduced the new UseSerilogRequestLogging() middleware, which condenses the important information about requests handled by ASP.NET Core into one clean, streamlined, request completion event. Check out the section §Taking control of log output to see how to set this up.

Because the UseSerilogRequestLogging() middleware runs in the request handling pipeline outside of ASP.NET Core MVC, the request completion event doesn’t include MVC-specific details like ActionId or ActionName by default.

To add these in, we can use an action filter and Serilog’s IDiagnosticContext. This interface lets us attach additional properties to the request completion event:

using System;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Serilog;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class SerilogMvcLoggingAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var diagnosticContext = context.HttpContext.RequestServices.GetService<IDiagnosticContext>();
diagnosticContext.Set(“ActionName”, context.ActionDescriptor.DisplayName);
diagnosticContext.Set(“ActionId”, context.ActionDescriptor.Id);
}
}

The filter can be attached to individual controllers or actions as [SerilogMvcLogging], but in this case it’s more likely you’ll want to add it globally to the MVC configuration in your Startup class:

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(opts =>
{
opts.Filters.Add<SerilogMvcLoggingAttribute>();
});
}

Just like that, your request completion events will be enriched with MVC details:

IDiagnosticContext is a powerful feature because it adds easy-to-correlate, space-efficient information to request logs. If you find that every web request ends up logging two or three additional events, consider condensing this down onto the request completion event using IDiagnosticContext – correlation will be easier, and you’ll reduce log noise, too!

Flatlogic Admin Templates banner

Leave a Reply

Your email address will not be published. Required fields are marked *