我在 program.cs 中有这个 Serilog 配置。
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,其中包含用户名 Enricher,但是 .Net Framework 和 .Net Core 的目标框架之间存在冲突,因此我无法使用此插件。
有什么想法吗?
startup.cs
中加载中间件app.UseMiddleware<LogUserNameMiddleware>();
) - Muflixapp.UseAuthentication()
之后分配它,但结果相同。有什么想法吗? - Cocowallaapp.UseMiddleware<LogUserNameMiddleware>()
可能最好放在app.UseMvc()
之前,确保任何身份验证中间件都在它之前。 - Josh Brown