将用户名添加到Serilog [英] Add Username into Serilog
问题描述
我在 program.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
.
Now i want to add HttpContext.Current.User.Identity.Name
into all log messages.
我尝试根据文档 https://github.com创建新的Enrich类/serilog/serilog/wiki/Configuration-Basics#enrichers
class UsernameEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory, HttpContext httpContext)
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
"Username", httpContext.User.Identity.Name));
}
}
但是与不知道 HttpContext 的 ILogEventEnricher 冲突.
我还尝试安装包含用户名Enricher的Nuget软件包 Serilog.Web.Classic ,但是目标框架.Net Framework和.Net Core之间存在冲突,因此我无法使用此插件.
I also tried to install Nuget package Serilog.Web.Classic which contains Username Enricher, but there is conflict between target framework .Net Framework and .Net Core therefore i cannot use this plugin.
有什么主意吗?
推荐答案
您可以创建一个中间件,将所需的属性放入LogContext.
You can create a middleware to put required property to 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);
}
}
还需要在记录器配置中添加以下内容:
Also you need to add the following to your logger configuration:
.Enrich.FromLogContext()
这篇关于将用户名添加到Serilog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!