我在 中有这个 Serilog 配置程序.cs
public class Program
{
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.Build();
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.WriteTo.MSSqlServer(Configuration.GetConnectionString("DefaultConnection"), "dbo.Log")
.Enrich.WithThreadId()
.Enrich.WithProperty("Version", "1.0.0")
.CreateLogger();
try
{
BuildWebHost(args).Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog()
.Build();
}
现在我想添加
HttpContext.Current.User.Identity.Name
进入所有日志消息。我尝试按照文档 https://github.com/serilog/serilog/wiki/Configuration-Basics#enrichers 创建新的 Enrich 类
class UsernameEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, HttpContext httpContext)
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
"Username", httpContext.User.Identity.Name));
}
}
但是和有冲突ILogEventEnricher 哪个不知道 HttpContext .
我也尝试安装 Nuget 包 Serilog.Web.Classic 其中包含 Username Enricher,但目标框架 .Net Framework 和 .Net Core 之间存在冲突,因此我无法使用此插件。
任何的想法 ?
最佳答案
您可以创建一个中间件来将所需的属性放入 LogContext。
public class LogUserNameMiddleware
{
private readonly RequestDelegate next;
public LogUserNameMiddleware(RequestDelegate next)
{
this.next = next;
}
public Task Invoke(HttpContext context)
{
LogContext.PushProperty("UserName", context.User.Identity.Name);
return next(context);
}
}
您还需要将以下内容添加到您的记录器配置中:.Enrich.FromLogContext()
在 Startup 中添加中间件 LogUserNameMiddleware
,还要注意中间件要加在UserAuthentication
后面,为了拥有context.User.Identity
初始化例如
app.UseAuthentication();
app.UseMiddleware<LogUserNameMiddleware>();
关于c# - 将用户名添加到 Serilog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51261177/