I create my own SeriLog receiver that implements ILogEventSink using the Example of creating a simple shell to record some information from users claim. To access the HttpContext in Core, I would usually inject IHttpContextAccessor into the instance, but the example shows IHttpContextAccessor to create the receiver instance in the extension method, for example.
public class MySink : ILogEventSink { private readonly IFormatProvider _formatProvider; public MySink(IFormatProvider formatProvider) { _formatProvider = formatProvider; } public void Emit(LogEvent logEvent) {
... then use the sink ...
var log = new LoggerConfiguration() .MinimumLevel.Information() .WriteTo.MySink() .CreateLogger();
How to access the current HttpContext in the receiver's Emit method? Or maybe there is a sink created by the DI framework, for example ?!
I have an MVC site working with an Asp.Net Core 2 base against the .NET 4.2.2 environment using Serilog.AspNetCore v2.1.0.
Update - Workaround
After the pointer from @tsimbalar, I created a middleware similar to the code below. In my StartUp.Configure method StartUp.Configure I add it using app.UseMiddleware<ClaimsMiddleware>(); after the authentication step of the application has been completed (otherwise, no applications will be downloaded).
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));
source share