2016-09-13 42 views
2

我正在使用NLog作为我的记录器。当我运行.exe进行日志记录时,一切正常,甚至通过Visual Studio进行调试,NLog仍然会写入文件。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> 

下面是从内部日志中的错误:

Error Error has been raised. Exception: System.Runtime.InteropServices.COMException (0x800700A1): The specified path is invalid. (Exception from HRESULT: 0x800700A1) 
    at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) 
    at NLog.Internal.FileAppenders.BaseFileAppender.WindowsCreateFile(String fileName, Boolean allowFileSharedWriting) 
    at NLog.Internal.FileAppenders.BaseFileAppender.TryCreateFileStream(Boolean allowFileSharedWriting) 
    at NLog.Internal.FileAppenders.BaseFileAppender.CreateFileStream(Boolean allowFileSharedWriting) 
    at NLog.Internal.FileAppenders.RetryingMultiProcessFileAppender.Write(Byte[] bytes) 
    at NLog.Targets.FileTarget.WriteToFile(String fileName, LogEventInfo logEvent, Byte[] bytes, Boolean justData) 
    at NLog.Targets.FileTarget.ProcessLogEvent(LogEventInfo logEvent, String fileName, Byte[] bytesToWrite) 
    at NLog.Targets.FileTarget.Write(LogEventInfo logEvent) 
    at NLog.Targets.Target.Write(AsyncLogEventInfo logEvent) 
+0

您是否检查nlog的内部日志文件是否有错误?也发现这个链接,可能是相同的问题:http://stackoverflow.com/questions/1672998/nlog-with-vs-2008-unit-test – rlee

+0

我试过,但同样的问题仍然发生。文件是用正确的文件名创建的,但文件是空的。 D = – TheNoob

+0

你为什么要登录到filetarget而不是memorytarget? – Julian

回答

1

不知道这是一个问题,但可以肯定它是:

从单元测试环境中读取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复位。

更新:在配置中启用throwExceptions。

也关于错误。您可能需要单元测试中的绝对路径。

+0

哦,非常感谢您的回复!我会试一试,让你知道。 =)再次感谢 – TheNoob

+0

我试过这个解决方案,但同样的问题仍然发生。感谢您的输入,虽然=)非常感谢 – TheNoob

+0

您是否尝试过在nlog中打开调试,并查看是否有任何内容nlog文件中记录? – Webezine

3

我发现所有的配置都驻留在单元测试项目的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>