使用Serilog和Asp.Net Core时将用户添加到日志上下文 [英] Add user to the log context when using Serilog and Asp.Net Core
问题描述
我正在尝试将Serilog与我的ASP.Net Core 1.0项目一起使用.我只是似乎无法将当前登录的用户添加到已记录的属性中.
I'm trying to use Serilog together with my ASP.Net Core 1.0 project. I just can't seem to get the current logged in user added to properties logged.
有人知道吗?
我已经尝试过了:
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中添加以下内容来触发它:
I trigger this in Startup.cs by adding:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
loggerFactory.AddSerilog();
app.EnrichLogger();
...
}
但这总是以匿名"作为用户名.
But this always ends up with an "Anonymous" as the Username.
预先感谢
SørenRokkedal
Søren Rokkedal
推荐答案
仅用几行代码,我就能获得经过身份验证的Active Directory用户.我对Core身份验证的经验不是很丰富,尤其是声称,但是这可能会让您如愿以偿,或者至少能为其他遇到与您类似的问题但使用AD的人提供帮助.
I was able to get the authenticated Active Directory user with just a few lines of code. I'm not very experienced with Core authentication, claims in particular, but perhaps this will get you on your way or at a minimum help others that come along with a similar problem to yours but with AD.
关键行是Enrich.FromLogContext()
和app.Use(async...
public class Startup
{
public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext() // Populates a 'User' property on every log entry
.WriteTo.MSSqlServer(Configuration.GetConnectionString("MyDatabase"), "Logs")
.CreateLogger();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.WithFilter(new FilterLoggerSettings
{
{ "Default", LogLevel.Information },
{ "Microsoft", LogLevel.Warning },
{ "System", LogLevel.Warning }
})
.AddSerilog();
app.Use(async (httpContext, next) =>
{
var userName = httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.Name : "unknown";
LogContext.PushProperty("User", !String.IsNullOrWhiteSpace(userName) ? userName : "unknown");
await next.Invoke();
});
}
}
对于通过IIS/Kestrel进行AD身份验证,web.config需要如下的forwardWindowsAuthToken
设置:
For AD Authentication via IIS/Kestrel the web.config requires a forwardWindowsAuthToken
setting as follows:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<aspNetCore ... forwardWindowsAuthToken="true" />
</system.webServer>
</configuration>
这篇关于使用Serilog和Asp.Net Core时将用户添加到日志上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!