Добавить пользователя в контекст журнала при использовании Serilog и Asp.Net Core
Я пытаюсь использовать Serilog вместе с моим проектом ASP.Net Core 1.0. Я просто не могу, чтобы текущий зарегистрированный пользователь был добавлен в свойства.
Кто-нибудь уже понял это?
Я попробовал это:
using System.Threading.Tasks;
using Serilog.Context;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using xxx.Models;
namespace xxx.Utils
{
public class EnrichSerilogContextMiddleware
{
private readonly RequestDelegate _next;
public EnrichSerilogContextMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
var username = httpContext.User.Identity.Name;
if (httpContext.User.Identity.IsAuthenticated)
{
var userFullName = (((ClaimsIdentity)httpContext.User.Identity).FindFirst(Member.FullnameClaimName).Value);
var userName = "[email protected]";
LoggerEnricher.AddEntryPointContext(userFullName, userName);
}
else
{
LoggerEnricher.AddEntryPointContext();
}
await _next(httpContext);
}
}
public static class LoggerEnricher
{
public static void AddEntryPointContext(string userFullName = null, string username = null)
{
if (!string.IsNullOrWhiteSpace(username) || !string.IsNullOrWhiteSpace(userFullName))
{
LogContext.PushProperty("Username", username);
LogContext.PushProperty("UserFullename", userFullName);
}
else
{
LogContext.PushProperty("Username", "Anonymous");
}
}
public static void EnrichLogger(this IApplicationBuilder app)
{
app.UseMiddleware<EnrichSerilogContextMiddleware>();
}
}
}
Я запускаю это в Startup.cs, добавив:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
loggerFactory.AddSerilog();
app.EnrichLogger();
...
}
Но это всегда заканчивается «Аноним» в качестве имени пользователя.
заранее спасибо
Сорен Роккедал