11

I'm creating my own SeriLog sink implementing ILogEventSink using the Building a Simple Sink example with the intent of logging some information from the users claims. To get access to HttpContext in Core, I'd normally inject in an instance of IHttpContextAccessor but the example shows creating an instance of the sink in an extension method e.g.

public class MySink : ILogEventSink
{
    private readonly IFormatProvider _formatProvider;

    public MySink(IFormatProvider formatProvider)
    {
        _formatProvider = formatProvider;
    }

    public void Emit(LogEvent logEvent)
    {
        // How to get HttpContext here?
    }
}

public static class MySinkExtensions
{
    public static LoggerConfiguration MySink(
              this LoggerSinkConfiguration loggerConfiguration,
              IFormatProvider formatProvider = null)
    {
        return loggerConfiguration.Sink(new MySink(formatProvider));
    }
}

... then to use the sink ...

var log = new LoggerConfiguration()
    .MinimumLevel.Information()
    .WriteTo.MySink()
    .CreateLogger();

How can I get access to the current HttpContext in the Emit method of the sink? Or is it possible to have the sink created by the DI framework for example?!

I have an MVC site running Asp.Net Core 2 framework against .Net 4.6.2 runtime using Serilog.AspNetCore v2.1.0.

Update - Workaround

After the pointer from @tsimbalar I created middleware similar to the code below. In my StartUp.Configure method I add it using app.UseMiddleware<ClaimsMiddleware>(); after the app authentication step has happened (otherwise there will be no claims loaded).

public class ClaimsMiddleware
{
    private static readonly ILogger Log = Serilog.Log.ForContext<ClaimsMiddleware>();
    private readonly RequestDelegate next;

    public ClaimsMiddleware(RequestDelegate next)
    {
        this.next = next ?? throw new ArgumentNullException(nameof(next));
    }

    public async Task Invoke(HttpContext httpContext)
    {
        if (httpContext == null) throw new ArgumentNullException(nameof(httpContext));

        // Get values from claims here
        var myVal = httpContext
                .User
                .Claims
                .Where(x => x.Type == "MyVal")
                .Select(x => x.Value)
                .DefaultIfEmpty(string.Empty)
                .SingleOrDefault();

        using (LogContext.PushProperty("MyVal", myVal))
        {
            try
            {
                await next(httpContext);
            }

            // Never caught, because `LogException()` returns false.
            catch (Exception ex) when (LogException(httpContext, ex)) { }
        }
    }

    private static bool LogException(HttpContext httpContext, Exception ex)
    {
        var logForContext = Log.ForContext("StackTrace", ex.StackTrace);

        logForContext.Error(ex, ex.Message);

        return false;
    }
}
Gavin Sutherland
  • 1,666
  • 3
  • 23
  • 36

2 Answers2

6

UPDATE I think you may want to look at this article : http://mylifeforthecode.github.io/enriching-serilog-output-with-httpcontext-information-in-asp-net-core/

The idea is to register a custom middleware that will add all the contextual information to the current LogContext during the request.

For it to work you must configure your logger with

Log.Logger = new LoggerConfiguration()
      // snip ....MinimumLevel.Debug()
      .Enrich.FromLogContext()                
      // snip ...
.CreateLogger(); 

This article by Nicholas Blumhardt may also help : https://blog.getseq.net/smart-logging-middleware-for-asp-net-core/


WARNING - Solution below does not work in this case

The solution below cannot work if the logger is registered early (in Program.Main() )

First of all, if you want to add extra information attached to the logged event, I believe what you want is an Enricher.

You could then :

  • Register IHttpContextAccessor into your ServiceCollection (for instance, using AddHttpContextAccessor()) : services.AddHttpContextAccessor();
  • Create an implementation of ILogEventEnricher that accepts IHttpContextAccessor in its constructor
  • When configuring your logger, inject IHttpContextAccessor (by adding an argument of type IHttpContextAccessor to Startup.Configure()
  • Add this enricher to your logger

The enricher could look something like https://github.com/serilog-web/classic/blob/master/src/SerilogWeb.Classic/Classic/Enrichers/ClaimValueEnricher.cs .

And you would configure your logger like this :

var logger = new LoggerConfiguration()
                .EnrichWith(new MyEnricher(contextAccessor))
                .WriteTo.Whatever()
                .CreateLogger();
Shawn Rakowski
  • 5,644
  • 2
  • 27
  • 29
tsimbalar
  • 5,790
  • 6
  • 37
  • 61
  • Thanks @tsimbalar. In the **configure** step you are passing the `contextAccessor` into an instance of a `MyEnricher` object. This isn't using dependency injection so how would I be getting the context if I'm configuring logging in the Program Main method before Startup (and subsequently `ConfigureServices`) has been called? – Gavin Sutherland Nov 07 '17 at 12:05
  • oh yes, if you are in Program Main , that cannot work .... mmmm not sure how that would work – tsimbalar Nov 07 '17 at 14:08
  • Thanks @tsimbalar. I had played around with a middleware solution previously with varying degrees of success. I was hoping there was a better way but I'll go revisit that and update ... – Gavin Sutherland Nov 09 '17 at 17:03
  • I had similar issue. Solved by writing Middleware as was suggested here. Might be useful to someone else: https://www.nuget.org/packages/Serilog.Enrichers.AspNetCore.HttpContext – Ihar Yakimush Jul 19 '18 at 16:22
4

I have been struggling trying to do the same and I finally found a proper solution.

Do not add the enricher when creating the Logger. You will have to add the enricher in the middleware where you can access the IServiceProvider. The key is that LogContext has a method, Push, that can add an enricher:

public async Task Invoke(HttpContext httpContext)
{
    IServiceProvider serviceProvider = httpContext.RequestServices;
    using (LogContext.Push(new LogEnricher(serviceProvider))) {
        await _next(httpContext);
    }
}

In the ConfigureServices, I add a services.AddScoped<HttpContextToLog>() call.

Then, I populate the HttpContextToLog object in several places, accessing it like this:

HttpContextToLog contextToLog = _serviceProvider.GetService<HttpContextToLog>();

in the Enrich method, in an IActionFilter, in an IPageFilter, etc.

Manu A.B.
  • 41
  • 1
  • 3