سؤال

I want to add a string to each row on my NLog output. The logic stays the same, trying to get the current user and if succeed, add the current user to the output.

I know how to implement it each time, but I want to set this template at one place and not repeat it on each writing.

هل كانت مفيدة؟

المحلول

The WindowsIdentityLayoutRenderer should probably give you what you want. You can choose to log either the Domain, the UserName, or both.

You would configure it something like this (untested) to your NLog.config file:

<targets>
    <target name="file" xsi:type="File" 
        layout="${longdate} | ${level} | ${logger} | ${windows-identity} | ${message}"
        fileName="${basedir}/${shortdate}.log" />
</targets>

This might not work in a low privilege environment.

How do you get the user name now? If you get it something like this:

HttpContext.Current.User.Identity.Name

Then you can use NLog's "aspnet-user-identity" LayoutRenderer, something like this:

<targets>
    <target name="file" xsi:type="File" 
        layout="${longdate} | ${level} | ${logger} | ${aspnet-user-identity} | ${message}"
        fileName="${basedir}/${shortdate}.log" />
</targets>

NLog's aspnet* LayoutRenderers are in NLog.Extended.sll, so you will need that dll in addition to NLog.dll.

نصائح أخرى

For those using custom authentication/authorization (or can't use the windows identity for some reason) and are using .NET core (3.*) you can use the MappedDiagnosticsContext to inject custom key-values.

As soon as you know the identity of the user you can set it like so:

using NLog;
//...
MappedDiagnosticsContext.Set("UserName", "Some user name");

Always make sure you do this in a Scoped manner (using .NET core Dependency Injection terms, or a Per Request Scope), since you don't want to mix up users when logging.

In your NLog config you can then read the value by using this syntax ${mdc:UserName}.

I'm using the following nuget packages:

  • nlog
  • nlog.web.aspnetcore

NLog ver. 4.6.4 introduced ${environment-user} that works on both Windows and Linux. It resolves to System.Environment.UserName

See also: https://github.com/NLog/NLog/wiki/Environment-User-Layout-Renderer

For ASP.NET application there is also ${aspnet-user-identity} for the user-identity currently logged on.

See also: https://github.com/NLog/NLog/wiki/AspNetUserIdentity-layout-renderer

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top