0

I want to create custom folder and logs with Microsoft.Extensions.NLog with ILogger. I want each users in my system to his personal folder. I create a target like this.

<target xsi:type="File"
            name="fileLog"
            fileName="${basedir}/${userName}/${userName}.log"
            maxArchiveFiles="50"
            archiveAboveSize="10000000"
            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}| ${uppercase:${level}} ${logger}|${message} ${exception:format=ToString,StackTrace}" />

And for example when I want to write a log userName to be transmited like argument.

Logger.LogError("Something went wrong. Id: {userName}", userName);

Thanks a lot for help!

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70
aXe
  • 51
  • 1
  • 4
  • You got some directions [here](https://stackoverflow.com/questions/37327129/nlog-dynamically-change-filename-using-nlog-config/52734579) – Ergis Apr 01 '21 at 15:38
  • @Ergis this is for NLog, not for Microsoft.Extensions.NLog, I tried, is not working. – aXe Apr 01 '21 at 15:40
  • I like to help, but your question is unclear. What does work and want doesn't? How is this a custom target? – Julian Apr 01 '21 at 16:29
  • @Julian The main idee is that I have users and I want to create separate logs for every user. For example in NLog, you can do this like GlobalDiagnosticsContext.Set("UserId_From_DB","42");, but in Microsoft.Extension.NLog for ILogger is different. How I can made this for ILogger, dynamic folder name for each user? – aXe Apr 01 '21 at 17:48

1 Answers1

1

I guess you can do this:

<nlog>
   <variable name="UserName" layout="${event-properties:item=userName:whenEmpty=App}" />

   <targets>
     <target xsi:type="File"
            name="fileLog"
            fileName="${basedir}/${UserName}/${UserName}.log"
            maxArchiveFiles="50"
            archiveAboveSize="10000000"
            layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}| ${uppercase:${level}} ${logger}|${message} ${exception:format=ToString,StackTrace}" />
   </targets>

   <rules>
      <logger name="*" minLevel="Debug" writeTo="fileLog" />
   </rules>
</nlog>

Then you can do this:

Logger.LogError("Something went wrong. Id: {userName}", userName);

See also: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-properties-with-Microsoft-Extension-Logging

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

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

See also: https://github.com/NLog/NLog/wiki/AspNet-User-Claim-layout-renderer

Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70