How to get MiniProfiler 4 logging to Serilog (or access within Middleware)?

759 Views Asked by At

I've been trying to get MiniProfiler.AspNetCore to work with Serilog.AspNetCore, or otherwise be able to log calls.

I tried creating a middleware with EndInvoke calling

private void EndInvoke(HttpContext context)
if (MiniProfiler.Current != null)
{
   Log.ForContext("MiniProfiler", JsonConvert.DeserializeObject<dynamic>(MiniProfiler.Current.ToJson()))
      .Verbose("Completed request in {Timing} ms", MiniProfiler.Current.DurationMilliseconds);
}

I'm trying to set it up similar to https://daveaglick.com/posts/easy-performance-and-query-logging-in-aspnet-with-serilog-and-miniprofiler which was done with the 3.0 not 4.0 version of MiniProfiler, as well as aspnet not aspnetcore.

Edit: Fixed the null issue, I was creating my middleware before the miniprofiler middleware, but it is still not logging to serilog/seq properly.

1

There are 1 best solutions below

0
On

Looks like part of the issue was I was missing

destructureObjects: true on the end of my ForContext() call

private void EndInvoke(HttpContext context)
{
    MiniProfiler.Current.Stop();
    if (MiniProfiler.Current != null)
    {
        Log.ForContext("MiniProfiler", JsonConvert.DeserializeObject<object>(MiniProfiler.Current.ToJson()), destructureObjects: true)
            .Debug("Completed request in {Timing} ms", MiniProfiler.Current.DurationMilliseconds);
    }
}

And the main reason was... I was filtering out verbose calls from sending to my seq server... changing it to debug made them show up right away.

So hope this question might help someone else in the future, but this does work with MiniProfiler 4 and AspNetCore 2. You will need Destructurama.JsonNet and add .Destructure.JsonNetTypes() on your LoggerConfiguration(), otherwise you'll just get empty items in your output.