Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add current user to NLog output

Tags:

c#

nlog

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.

like image 342
Shahar Avatar asked Nov 19 '13 17:11

Shahar


People also ask

What is Basedir in NLog?

${basedir} — Directory where the application runs, aka. AppDomain.BaseDirectory.

How do you use NLog for multiple projects in the same solution?

How do you use NLog for multiple projects in the same solution? If you want to log in other projects within the solution, just reference NLog. dll directly in each of the projects and use it. But now you only need to configure NLog in your main application.


1 Answers

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.

like image 184
wageoghe Avatar answered Sep 19 '22 18:09

wageoghe