问题
I was using "NLog.Extensions.Logging" for logging and need to log user identity and found that it is possible with "NLog.Web.AspNetCore". "nlog.config" file is configured to log the "aspnet-user-identity". However, when I look at logs, user identity part is always empty string, the other columns are look pretty good. Am I missing something?
A part of my configuration file is here:
<extensions>
<assembly="NLog.Web.AspNetCore" />
</extensions>
<parameter name="@identity" layout="${aspnet-user-identity}"/>
<logger name="*" minlevel="Trace" appendTo="database"/>
And an insert command insert a log to db with "@identity" parameter, but it is always empty like I said.
回答1:
I think I have found the issue,
There was an breaking change, The IHttpContextAccessor service is not registered by default anymore. (See announcement)
So add in your startup.cs:
public void ConfigureServices(IServiceCollection Services)
{
//call this in case you need aspnet-user-authtype/aspnet-user-identity
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
回答2:
Accepted answer didn't worked for my case (using JwtSecurityToken on ASP.NET Core 3.1), Later realized that I just forgot to add the ClaimTypes.Name on my JwtSecurityToken Claims.
Now its working and no need to register IHttpContextAccessor.
回答3:
I found this question while searching for "asp.net core nlog username". Eventually I found the solution and I am logging it here for posterity.
Problem
How do I include the currently logged in user's username in my NLog log messages?
Solution
I am using NLog inside of my ASP.NET Core web app. I tried using the ${aspnet-user-identity}
layout renderer, but determined that the value was empty because we were using custom authentication.
After doing some digging, I figured out that I could access values stored as a ASP.NET Session variable from NLog. So, after I authenticated the user, I stuffed their username into a session variable and voila!
Here is the code I call after authenticating the user:
// Store username in session so we can access it from NLog logs.
httpContext.Session.SetString("NlogUser", contact.Username);
Here is what the layout renderer line in the nlog.config looks like
<parameter name="@identity" layout="${aspnet-session:variable=NlogUser}"/>
Here is the corresponding NLog documenation for the AspNetSession layout renderer.
来源:https://stackoverflow.com/questions/40715331/net-core-nlog-web-aspnet-user-identity-is-empty