Net Core NLog.Web "aspnet-user-identity" 是空的?

Net Core NLog.Web "aspnet-user-identity" is empty?

我正在使用 "NLog.Extensions.Logging" 进行日志记录,需要记录用户身份,发现可以使用 "NLog.Web.AspNetCore"。 "nlog.config" 文件配置为记录 "aspnet-user-identity"。但是,当我查看日志时,用户身份部分始终为空字符串,其他列看起来还不错。我错过了什么吗?

我的部分配置文件在这里:

<extensions>
  <assembly="NLog.Web.AspNetCore" />
</extensions>

<parameter name="@identity" layout="${aspnet-user-identity}"/>

<logger name="*" minlevel="Trace" appendTo="database"/>

插入命令使用“@identity”参数将日志插入数据库,但就像我说的那样它总是空的。

我想我已经找到问题了,

发生了重大变化,默认情况下不再注册 IHttpContextAccessor 服务。 (See announcement)

所以添加你的 startup.cs:

public void ConfigureServices(IServiceCollection Services)
{
    //call this in case you need aspnet-user-authtype/aspnet-user-identity
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

我在搜索“asp.net 核心 nlog 用户名”时发现了这个问题。最终我找到了解决方案,并将其记录在这里以供后代使用。

问题

如何在我的 NLog 日志消息中包含当前登录用户的用户名?

解决方案

我在 ASP.NET 核心网络应用中使用 NLog。我尝试使用 ${aspnet-user-identity} 布局渲染器,但确定该值为空,因为我们使用的是自定义身份验证。

经过一些挖掘后,我发现我可以从 NLog 访问存储为 ASP.NET 会话变量的值。因此,在我对用户进行身份验证后,我将他们的用户名填充到会话变量中,瞧!

这是我在验证用户后调用的代码:

// Store username in session so we can access it from NLog logs.
httpContext.Session.SetString("NlogUser", contact.Username);

这是 nlog.config 中的布局渲染器行的样子

<parameter name="@identity" layout="${aspnet-session:variable=NlogUser}"/>

这是 AspNetSession layout renderer 的相应 NLog 文档。

已接受的答案对我的情况无效(在 ASP.NET Core 3.1 上使用 JwtSecurityToken), 后来意识到我只是忘了在我的 JwtSecurityToken 声明中添加 ClaimTypes.Name。

现在可以使用了,无需注册 IHttpContextAccessor。

如果您最近升级了 ASP.NET 核心,您可能需要在 program.cs 中以不同方式配置 NLog:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder
                    .CaptureStartupErrors(true)
                    .UseIISIntegration()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseStartup<Startup>()
                    .ConfigureLogging((hostingContext, logging) =>
                    {
                        //logging.AddNLog(); //<--- Can remove (NLog.Extensions.Logging)
                    })
                    ;
            })
            .UseNLog(); // <--- Call UseNLog off of IHostBuilder (NLog.Web)
}

https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3