using AppData location in NLog

Viewed 24309

My NLog targets is like this:

<targets>
  <target xsi:type="Console" name="console" 
    layout="${longdate}|${level}|${message}" />
  <target xsi:type="File" name="ErrorLog" fileName="${basedir}/error.txt"
          layout="${longdate}
          Trace: ${stacktrace} 
          ${message}" />
  <target xsi:type="File" name="AccessLog" fileName="${basedir}/access.txt"
          layout="${shortdate} | ${message}" />
</targets>

But this causes problems if the user isn't an admin on their machine, because they will not have write access to "Program Files". How can I get something like %AppData% to NLog instead of BaseDir?

5 Answers

You're looking for the NLog special folders.

Example:

...fileName="${specialfolder:folder=ApplicationData}/Program/file.txt"...

For logging to the project directory:

While the previous answers work for the original question, searching for how to log to the project APP_DATA directory leads to this question. And while bkaid's answer works for ASP.NET and for using the APP_DATA folder specifically, for .NET Core and .NET 5 the solution is a bit different, because that motif has been abandoned in favor of defining a wwwroot folder for only those things which should be served, and the remainder being private. The answer for .NET Core/5, then, is to write to the solution root directory:

  1. First, ensure the NLog.Web.AspNetCore assembly is added to nlog.config:
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
    </extensions>
    
  2. Then use one of the layout renderers provided by that extension, in this case ${aspnet-appbasepath} which references the solution root directory:
    <targets>
        <target name="file"
                type="File"
                xsi:type="File"
                fileName="${aspnet-appbasepath}/log/${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}"/>
    </targets>
    

This will write the file to <solution folder>/log/2021-07-01.log, which will never be served by the public-facing website. Other layout renderers provided by this assembly are listed on the NLog website.

Related