Is there a way to log the ASP User ID, rather than the username?
I've looked through: https://github.com/NLog/NLog/wiki/Layout-Renderers but can't see anything obvious.
Currently we are using ${aspnet-user-identity} but that only logs the username, which can change, therefore causes problems with the logs.
Type:
NLog version:
v4.0.1
Platform:
.Net 4.5
Current NLog config
xml
Thanks,
Paul
This is currently not there, but maybe easy to add.
Where is the ID stored? As IIdentity (httpContext.Current.User) only has a Name?https://msdn.microsoft.com/en-us/library/system.security.principal.iidentity(v=vs.110).aspx
We are using a IdentityUser to get the ID.
https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.entityframework.identityuser%28v=vs.108%29.aspx
We have no EntityFramework implementation. But it's easy to create your own:
something like this:
``` c#
[LayoutRenderer("IdentityUser")]
public class IdentityUserLayoutRenderer : LayoutRenderer
{
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
string name= ...; //todo
builder.Append(name);
}
}
//todo register
```
See http://nlog-project.org/2015/06/30/extending-nlog-is-easy.html
It was pretty easy to create my own!
I was going to add it to the project but it needs a reference to Microsoft.AspNet.Identity.Core and not sure if that would be something you would want to add.
Here's the code in case some one else wants it:
``` c#
using Microsoft.AspNet.Identity;
using NLog;
using NLog.LayoutRenderers;
using NLog.Web.LayoutRenderers;
using System.Text;
namespace IPoint.Web.Helpers.NLog
{
[LayoutRenderer("aspnet-user-id")]
public class AspNetUserIdLayoutRenderer : AspNetLayoutRendererBase
{
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
var context = HttpContextAccessor.HttpContext;
if (context.User?.Identity == null)
{
return;
}
builder.Append(context.User.Identity.GetUserId());
}
}
}
```
Thanks,
Paul
We try to keep the dependencies a low a possible, so adding this is indeed difficult.
Thanks for sharing!
Most helpful comment
It was pretty easy to create my own!
I was going to add it to the project but it needs a reference to
Microsoft.AspNet.Identity.Coreand not sure if that would be something you would want to add.Here's the code in case some one else wants it:
``` c#
using Microsoft.AspNet.Identity;
using NLog;
using NLog.LayoutRenderers;
using NLog.Web.LayoutRenderers;
using System.Text;
namespace IPoint.Web.Helpers.NLog
{
[LayoutRenderer("aspnet-user-id")]
public class AspNetUserIdLayoutRenderer : AspNetLayoutRendererBase
{
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
var context = HttpContextAccessor.HttpContext;
}
```
Thanks,
Paul