我在 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));
}
}
但是与不知道 HttpContext 的 ILogEventEnricher 冲突。
我还尝试安装包含用户名Enricher的Nuget软件包 Serilog.Web.Classic ,但是目标框架.Net Framework和.Net Core之间存在冲突,因此我无法使用此插件。
有什么想法吗?
答案 0 :(得分:9)
您可以创建一个中间件,将所需的属性放入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()
答案 1 :(得分:5)
如果您使用的是Serilog.AspNetCore,则添加身份验证/用户属性非常容易。
app.UseSerilogRequestLogging(options =>
{
options.EnrichDiagnosticContext = PushSeriLogProperties;
});
public void PushSeriLogProperties(IDiagnosticContext diagnosticContext, HttpContext httpContext)
{
diagnosticContext.Set("SomePropertyName", httpContext.User...);
}
答案 2 :(得分:4)
@Alex Riabov建议的方法存在很多问题。
Dispose
推送的属性Invoke
方法是异步的,因此您不仅可以return next()
,还需要await next()
UseSerilogRequestLogging()
中间件记录。如果在到达属性之前将其弹出,则该属性将为空。要修复它们,我建议进行以下修改。
在中间件中:
public async Task Invoke(HttpContext context)
{
using (LogContext.PushProperty("UserName", context.User.Identity.Name ?? "anonymous"))
{
await next(context);
}
}
在Startup.cs
中:
appl.UseRouting()
.UseAuthentication()
.UseAuthorization()
.UseMiddleware<SerilogUserNameMiddleware>()
.UseSerilogRequestLogging()
.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
endpoints.MapHealthChecks("/health");
});
答案 3 :(得分:2)
使用中间件的另一种方法是使用动作过滤器。
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Serilog.Context;
namespace Acme.Widgets.Infrastructure
{
public class LogEnrichmentFilter : IActionFilter
{
private readonly IHttpContextAccessor httpContextAccessor;
public LogEnrichmentFilter(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public void OnActionExecuting(ActionExecutingContext context)
{
var httpUser = this.httpContextAccessor.HttpContext.User;
if (httpUser.Identity.IsAuthenticated)
{
var appUser = new AppIdentity(httpUser);
LogContext.PushProperty("Username", appUser.Username);
}
else
{
LogContext.PushProperty("Username", "-");
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Do nothing
}
}
}
在您的Startup.ConfigureServices
中,您需要:
IHttpContextAccessor
添加到IoC容器LogEnrichmentFilter
添加到IoC容器中,并以请求为范围LogEnrichmentFilter
注册为全局操作过滤器 Startup.cs
:
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<LogEnrichmentFilter>();
services.AddMvc(o =>
{
o.Filters.Add<LogEnrichmentFilter>();
});
然后,您应该在日志上下文中拥有在MVC action invocation pipeline中运行的代码的当前用户名。我想如果您使用resource filter而不是操作过滤器,用户名将附加到更多日志条目中,因为它们在管道中运行得更早(我只是发现了这些!)>