【发布时间】:2017-02-15 05:26:19
【问题描述】:
我正在尝试将 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 = "anyone@gmail.com";
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();
...
}
但这总是以“匿名”作为用户名。
提前致谢
索伦·罗克达尔
【问题讨论】:
-
您是否尝试在身份验证后将其添加到您的管道中?
-
不确定你的意思
-
我的意思是在调用
app.UseAuthentication(....);之后调用app.EnrichLogger();,或者无论你的身份验证方法是什么。在用户通过身份验证之前,您在管道中过早注入记录器,因此它始终是匿名的。 -
我在调用之前有 app.UseIdentity() 来丰富记录器
-
@SørenRokkedal .. 感谢这是一篇旧帖子,但你有没有想过这个问题?谢谢
标签: asp.net-core serilog