Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# NLog与单元测试_C#_Visual Studio_Unit Testing_Nlog - Fatal编程技术网

C# NLog与单元测试

C# NLog与单元测试,c#,visual-studio,unit-testing,nlog,C#,Visual Studio,Unit Testing,Nlog,我正在为我的记录器使用NLog。当我运行一个.exe,甚至通过VisualStudio进行调试时,在日志记录时一切正常,NLog仍然会写入文件 但是,如果我运行一个通过单元测试调用记录器的对象,则会创建该文件,但它是空的。我是否需要向配置中添加额外的设置/规则,以使NLog写入单元测试下的文件 我可以为此模拟NLog,并且没有日志转储,但我想在我决定模拟NLog之前看看是否可以让它工作。尽管这只发生在单元测试中,在其他情况下也可以工作,但下面是我的日志配置和代码。我漏掉了文件名 public s

我正在为我的记录器使用NLog。当我运行一个.exe,甚至通过VisualStudio进行调试时,在日志记录时一切正常,NLog仍然会写入文件

但是,如果我运行一个通过单元测试调用记录器的对象,则会创建该文件,但它是空的。我是否需要向配置中添加额外的设置/规则,以使NLog写入单元测试下的文件

我可以为此模拟NLog,并且没有日志转储,但我想在我决定模拟NLog之前看看是否可以让它工作。尽管这只发生在单元测试中,在其他情况下也可以工作,但下面是我的日志配置和代码。我漏掉了文件名

public static void Info(string app, string m)  => EngineLogger.Logger.Info($"{app} : {m}");



<targets>
    <target name="infoFile"
            xsi:type="File"
            layout="${date:format=yyyy-MM-dd HH\:mm\:ss} ${pad:padding=5:inner=${level:uppercase=true}} ${logger} ${message}"
            fileName="leftoutForQuestion"
            keepFileOpen="false"
            encoding="iso-8859-2" />
    <target name="errorFile"
            xsi:type="File"
            layout="${date:format=yyyy-MM-dd HH\:mm\:ss} ${pad:padding=5:inner=${level:uppercase=true}} ${logger} ${message}"
            fileName="leftOutForQuestion"
            keepFileOpen="false"
            encoding="iso-8859-2" />
  </targets>
  <rules>
    <logger name="*" minlevel="Debug" maxlevel="Info" writeTo="infoFile" />
    <logger name="*" minlevel="Warn" maxlevel="Fatal" writeTo="errorFile" />
  </rules>

不确定这是否是问题所在,但可以肯定的是:

从单元测试环境中读取NLog.config可能比较困难,因此在单元测试中从字符串中读取配置更为健壮。我们使用助手:

    protected XmlLoggingConfiguration CreateConfigurationFromString(string configXml)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(configXml);

        return new XmlLoggingConfiguration(doc.DocumentElement, Environment.CurrentDirectory);
    }
然后:

 LogManager.Configuration = CreateConfigurationFromString(@"
            <nlog throwExceptions='true'>
                <targets><target name='debug' type='debug' layout='${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='info' appendto='debug'>
                        <filters>
                            <whencontains layout='${message}' substring='msg' action='ignore' />
                        </filters>
                    </logger>
                </rules>
            </nlog>");
LogManager.Configuration=CreateConfigurationFromString(@)
");
不要忘记在每次测试之前或之后重置
LogManager.Configuration

更新:通过配置中的异常启用


还有关于这个错误。在单元测试中可能需要一个绝对路径

我发现所有配置都位于单元测试项目的app.config中,而不是NLog.config文件。确保先声明配置部分,然后声明NLog配置。下面是我的示例app.config

    <configuration>
      <configSections>

         <section name="nlog"
                    type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>


      <target name="file" xsi:type="File"
             layout="${longdate} ${logger} ${message}"
             fileName="${basedir}/logs/${shortdate}.log" />

    </targets>
   <rules>
       <logger name="*" minlevel="Trace" writeTo="file"/>

    </rules>

  </nlog>
</configuration>

当并行执行单元测试时,最好为每个并行执行使用独立的NLog LogFactory:

LogFactory logFactory = new LogFactory();
logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, true, logFactory); 
Logger logger = logFactory.GetCurrentClassLogger();
另见

如果需要从字符串而不是文件加载NLog配置:

string currentDir = System.IO.Directory.GetCurrentDirectory();
System.IO.StringReader sr = new System.IO.StringReader(xmlString);
System.Xml.XmlReader xr = System.Xml.XmlReader.Create(sr);
logFactory.Configuration.Configuration = new NLog.Config.XmlLoggingConfiguration(xr, currentDir);

另请参见

是否检查了nlog的内部日志文件中的错误?也发现这个链接可能是同样的问题:我也尝试过,但同样的问题仍然发生。使用正确的文件名创建文件,但该文件为空。D=为什么要登录到filetarget而不是memorytarget?因为它可以工作?我不确定这个目标是如何导致它只在单元测试下被破坏的?同样,如果我只运行一个exe,那么日志记录将不会出现任何问题。除非我错过了什么。。。非常感谢你的回复!我将尝试一下,并让您知道。=)感谢againi尝试了这个解决方案,但同样的问题仍然发生。感谢您的输入,尽管=)非常感谢您是否尝试在nlog中打开调试并查看内部nlog文件中是否记录了任何内容?
string currentDir = System.IO.Directory.GetCurrentDirectory();
System.IO.StringReader sr = new System.IO.StringReader(xmlString);
System.Xml.XmlReader xr = System.Xml.XmlReader.Create(sr);
logFactory.Configuration.Configuration = new NLog.Config.XmlLoggingConfiguration(xr, currentDir);