3
votes

I have a solution I built using .NET 4.7. This solution has two projects:

  • A class library (.NET 4.7.2)
  • A Unit Test Project (.NET Framework)

I'm trying to migrate this solution to use .NET Standard | Core.

I have successfully transferred the class library to a .NET Standard 2.0 project. I have also transferred the Unit Test Project to a .NET Core 2.0 mstest project. Everything compiles. I can run my tests as expected. However, no logs are getting written via NLog.

In my .NET 4.7 version of the solution, when I ran the unit tests, an actual log file was written via NLog. However, in the new .NET Standard | Core implementation, this log file is not getting written. I have the following two files in my mstest project:

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>

nlog.config

<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"  
    xsi:schemaLocation="NLog NLog.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    autoReload="true"
    internalLogFile="c:\temp\console-example-internal.log"
    internalLogLevel="Info" >
  <targets>
    <target name="myLogs" xsi:type="File" deleteOldFileOnStartup="true" fileName="${basedir}/logs/MyLogs.json" createDirs="true" keepFileOpen="true" encoding="utf-8" layout="${message}" />
    <target name="traceLogs" xsi:type="File" deleteOldFileOnStartup="true" fileName="${basedir}/logs/trace.log" createDirs="true" keepFileOpen="true" encoding="utf-8" layout="[${longdate}] ${message}${exception:format=ToString}"></target>
  </targets>

  <rules>
    <logger name="MyLogger" minlevel="Info" writeTo="myLogs" />
    <logger name="TraceLogger" minlevel="Trace" writeTo="traceLogs" />
  </rules>
</nlog>

In my mstest project, I've also added references to:

  • Microsoft.Extensions.DependencyInjection
  • NLog
  • NLog.Extensions.Logging

I followed the steps outlined here. Except, I didn't do anything beyond step 2. Do I need that stuff for a mstest project? If so, where? It seems like a lot of additional stuff for something that was already working.

1

1 Answers

5
votes

When running unit tests, it's hard to find the nlog.config as implementations will move the DLLs (and most of the time not the nlog.config) to temporary folders.

It's recommend to configure NLog from code in an unit test project. (how-to here)

Another option is to load the NLog config file manually. You need to provide the path to nlog.config to the XmlLoggingConfiguration contructor:

LogManager.Configuration = new XmlLoggingConfiguration(pathToNLogConfig);

Off topic but related:

In the unit test it's recommend to write the eventlogs not to a file, but in memory, e.g. the Memory target. It makes the unit test more robust.