c# - 将用户名添加到 Serilog

标签 c# asp.net-core logging serilog

我在 中有这个 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/

相关文章:

c# - 设置正确的输入/输出 Devexpress gridcontrol 单元掩码

c# - 如何将半透明设置为背景,而不是 wp8 的前景?

.net - (TTFB) 某些特定请求花费的时间比执行实际请求的时间长

c# - 如何在没有角色的情况下使用 ASP.NET Core Identity?

java - Jboss 上的 Logback 在记录时重复前缀和新行

c# - 将 Action 转换为 LambdaExpression

c# - 套接字发送客户端列表

asp.net-mvc - 如何在 ASP.NET Core 的 Razor Pages 中设置全局变量?

Mysql Slow.log 用户特定

logging - 全局日志记录的正确方法