在Serilog中通过LogContext添加用户名

huangapple go评论75阅读模式
英文:

Add Username via LogContext in Serilog

问题

我正在.NET Core 6.0 Web API应用程序中使用Serilog进行日志记录。我想将已登录用户的用户名添加到日志中。我的中间件如下:

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);
    }
}

在Program.cs中:

var _logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)    
    .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
    .Enrich.FromLogContext()
    .CreateLogger();

Log.Logger = _logger;
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(_logger);

以及在appsettings中:

"Serilog": {
    "MinimumLevel": {
        "Default": "Information",
        "Override": {
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "WriteTo": [
        {
            "Name": "File",
            "Args": {
                "path": "C:\\Debug\\webapi-.log",
                "rollingInterval": "Day",
                "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {CorrelationId} {Level:u3}] {Username} {Message:lj}{NewLine}{Exception}"
            }
        }
    ]
}

但是用户名称未写入日志。我可以在中间件中看到用户名,但在日志中看不到。我漏掉了什么?

注意:请确保Serilog的版本和配置正确,并且确保在中间件中正确设置了用户名属性。

英文:

I am using Serilog for logging in .NET Core 6.0 Web API application. I want to add logged user name to logs. My middleware is

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);
    }
}

and in Program.cs

var _logger = new LoggerConfiguration()
 .ReadFrom.Configuration(builder.Configuration)    
 .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
 .Enrich.FromLogContext()
 .CreateLogger();

Log.Logger = _logger; //new 
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(_logger);

and in appsettings

 "Serilog": {
"MinimumLevel": {
  "Default": "Information",
  "Override": {
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
  }
},
"WriteTo": [
  {
    "Name": "File",
    "Args": {
      "path": "C:\\Debug\\webapi-.log",
      "rollingInterval": "Day",
      "outputTemplate": "[{Timestamp:yyyy-MM-dd HH:mm:ss} {CorrelationId} {Level:u3}] {Username} {Message:lj}{NewLine}{Exception}"
    }
  }
]

But User name is not writing in logs. I can see user name in middleware but not in logs. What am I missing here?

答案1

得分: 0

属性名称区分大小写,您正在推送 UserName,但模板中使用的是 {Username}。统一名称,同时您可能希望在 PushProperty 前后包装使用:

public async Task Invoke(HttpContext context)
{
    using (LogContext.PushProperty("Username", context.User.Identity.Name))
    {
        await next(context);
    }
}
英文:

Property names a case-sensitive, you are pushing UserName but template has {Username}. Consolidate names, also you might want to wrap the PushProperty in using:

public async Task Invoke(HttpContext context)
{
    using (LogContext.PushProperty("Username", context.User.Identity.Name))
    {
        await next(context);
    }
}

huangapple
  • 本文由 发表于 2023年6月29日 18:54:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定