How to log the selected ASP.NET Core MVC route?

Viewed 1622

Is there a simple way to log (using nlog, e.g. log.Debug(…)) the selected route in an ASP.NET Core MVC application? I use HttpGet/HttpPost attributes to define my routes, and I am looking for a simple way to log the route that MVC chooses to handle for each incoming request.

Note: Similar questions have been answered, but they relate to debugging and analyzing routes:

For my purposes, though, I just want to know which route MVC chose to handle for the request and have it logged. (And, ideally, I don't want to add a log to each controller method; there must be some way to do this once generically for all incoming requests.)

2 Answers

a simple generic way of logging all request is using a registered middleware component.

    public class PerformanceMiddleware
    {
        private readonly RequestDelegate _next;

        public PerformanceMiddleware(RequestDelegate requestDelegate)
        {
            _next = requestDelegate;
        }

        public Task Invoke(HttpContext httpContext)
        {
            var watch = new Stopwatch();
            watch.Start();

            var nextTask = _next.Invoke(httpContext);
            nextTask.ContinueWith(t =>
            {
                var time = watch.ElapsedMilliseconds;
                var requestString = $"[{httpRequest.Method}]{httpRequest.Path}?{httpRequest.QueryString}";
                if (t.Status == TaskStatus.RanToCompletion)
                {
                    .. log.Info ..($"{time}ms {requestString}");
                }
                else
                {
                    .. log.Warn ..($"{time}ms [{t.Status}] - {requestString}", t.Exception?.InnerException);
                }
            });
            return nextTask;
        }
    }

this also logs the execution time

In your startup you register it as the first, before UseMvc and any other middleware components.

            app.UseMiddleware<PerformanceMiddleware>();

On IIS, you can use the web.config file. In this file, by default, there is an option stdoutLogEnabled=false. Switch it to true. A log will be generated with the info you want.

Edit : Updated my answer to specify it's only correct for IIS according to the comments below

Related