LogManager.configuration - null

I added NLog using nuget for the project, and added NLog.config. I run the debugger and get a NullReferenceException because LogManager.Configuration is null:

LogManager.Configuration.AddTarget("sentinel", sentinalTarget);

This line of code is executed in a static constructor.

  • NLog.config is at the root of the project along with web.config.
  • This happens in the visual studio debugger.
  • NLog.config property "Copy to output directory" = "Always copy"
  • I updated NLog.config throwExceptions = "true" and at runtime LogManager.ThrowExceptions was false, so I suspect a problem with config
  • I tried to delete targets with the name: viewer, DbWin and related rules.

The contents of NLog.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" autoReload="true" throwExceptions="false"> <variable name="appName" value="YourAppName" /> <targets async="true"> <target xsi:type="File" name="default" layout="${longdate} - ${level:uppercase=true}: ${message}${onexception:${newline}EXCEPTION\: ${exception:format=ToString}}" fileName="${specialfolder:ApplicationData}\${appName}\Debug.log" keepFileOpen="false" archiveFileName="${specialfolder:ApplicationData}\${appName}\Debug_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30" /> <target xsi:type="EventLog" name="eventlog" source="${appName}" layout="${message}${newline}${exception:format=ToString}"/> <target xsi:type="NLogViewer" name="viewer" address="udp://127.0.0.1:9999"/> <target xsi:type="OutputDebugString" name="DbWin" layout="Log4JXmlEventLayout"> <layout xsi:type="Log4JXmlEventLayout" /> </target> </targets> <rules> <logger name="*" writeTo="default" minlevel="Info" /> <logger name="*" writeTo="eventlog" minlevel="Error" /> <logger name="*" minlevel="Debug" writeTo="viewer" /> <logger name="*" minlevel="Trace" writeTo="DbWin" /> </rules> </nlog> 

Refresh
I discovered the source. The problem only occurs when performing unit tests. Running a full application (web application) does not exist. I copied the NLog.config file to the unit test home directory. The problem still exists when doing unit tests.

+8
c # nlog
source share
1 answer
  • Copy NLog.config to the top-level folder of Test Projects
  • Add DeploymentItemAttribute to test classes ( more )

Like this:

 [TestClass] [DeploymentItem("ProjectName\\NLog.config")] public class GeneralTests 

Alternatively, you can load the configuration programmatically:

LogManager.Configuration = new XmlLoggingConfiguration(@"c:\path\to\NLog.config")

+13
source share

All Articles