LittleMygler
LittleMygler

Reputation: 632

Make NLog log even when testing with UnitTests c#

As the title says, I want my Logger to not be ignored when running unit tests using XUnit. I want it still to log. If this is possible, how can it be done?

Here is my config

<?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">

  <targets>
    <target name="log"
       xsi:type="File"
       fileName="${basedir}/logs/log.${longdate:cached=true}.log"
       layout="${message}"
       archiveFileName="${basedir}/logs/archives/log.${shortdate}.{#}.log"
       archiveAboveSize="5242880"
       archiveEvery="Day"
       archiveNumbering = "Rolling"
       maxArchiveFiles="20"
     />
    <target name="logconsole" xsi:type="Console" />
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="logconsole" />
    <logger name="*" minlevel="trace" writeTo="log" />
  </rules>
</nlog>

I just have a backend and no frontend, so when I run the tests I want to see that everything logs :)

Upvotes: 1

Views: 3223

Answers (1)

Julian
Julian

Reputation: 36730

You could use NLog in unit tests. Unfortunately it's difficult for NLog to find the path to the nlog.config as unit test frameworks move the binaries between folders - and not the nlog.config.

Also it's different in different environments/frameworks (NUnit, xUnit, MSTest, .NET full, .NET Core)

You could do:

  • Write the configuration in C#. See Docs
  • Or tell NLog the path to the config:

    LogManager.Configuration = new XmlLoggingConfiguration("pathToNLogConfig/nlog.config");
    

Also recommend for logging in unit tests, write to the memory target instead of file/database etc. You could also retrieve in code the logged events. See memory target docs

Upvotes: 2

Related Questions