Home > Net >  How to add a log file to wwwroot folder using XML's <target fileName=""/>
How to add a log file to wwwroot folder using XML's <target fileName=""/>

Time:10-09

I am trying to add a log folder with log files to my project's wwwroot folder using Nlog.Config. The code is in XML and I have no knowledge of it.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<!-- the targets to write to -->
<targets>
    <!-- write logs to file  -->
    <target name="allfile" xsi:type="File"
            fileName="\DemoLogs\nlog-all-${shortdate}.log"/> <!-- fileName needs a change -->
</targets>

<!-- rules to map from logger name to target -->
<rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />
</rules>

CodePudding user response:

Problem solved, I used the link sent by user: Rolf Kristensen and I found that ${aspnet-webrootpath}\yourPath will do the job. I change the code, see changes below.

Changes:

  • Changed fileName="\DemoLogs\nlog-all-${shortdate}.log" to fileName="${aspnet-webrootpath}\DemoLogs\nlog-all-${shortdate}.log" to make a new link.
  • Added throwConfigExceptions="true" to the as such <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwConfigExceptions="true"> for debugging.

Errors:

As I run the program it gave me 3 inner errors:

  • NLogConfigurationException: 'FileTarget' cannot assign property 'FileName'='${aspnet-webrootpath}\DemoLogs\nlog-all-${shortdate}.log'. Error: Failed to parse layout containing type: aspnet-webrootpath
  • NLogConfigurationException: Failed to parse layout containing type: aspnet-webrootpath
  • ArgumentException: LayoutRenderer type-alias is unknown: 'aspnet-webrootpath'. Extension NLog.Web.AspNetCore not included?

Solution

To fix those errors I used HitHub's solution and added this to the code:

<extensions>
    <add assembly="NLog.Web.AspNetCore"/>
</extensions>

Finall Code:

The code below works 100%, tried it, saved a log file in the wwwroot folder.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  throwConfigExceptions="true">
<extensions>
    <add assembly="NLog.Web.AspNetCore"/>
</extensions>

<!-- the targets to write to -->
<targets>
    <!-- write logs to file  -->
    <target name="allfile" xsi:type="File"
            fileName="${aspnet-webrootpath}\DemoLogs\nlog-all-${shortdate}.log"/>
</targets>

<!-- rules to map from logger name to target -->
<rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />
</rules>
  • Related