NLog和单元测试 [英] NLog and Unit Testing

查看:88
本文介绍了NLog和单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NLog作为记录器.当我运行.exe甚至通过Visual Studio进行调试时,登录时一切正常,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)

我发现所有配置都驻留在单元测试项目的app.config中,而不是NLog.Config文件.确保先声明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>

I am using NLog for my logger. Everything works fine when logging when I run an .exe, or even debug through Visual Studio, NLog will still write to the file.

But, if I run an object that calls the logger through a Unit test, the file is created but it is empty. Is there an extra setting/rule I need to add to the config to have NLog write to files under unit tests?

I could mock NLog for this and not have log dumps, but I'd like to see if I can get this to work before I decide to just mock NLog. Even though this is only happening in unit tests and is working otherwise, here is my config and code for logging. I left out the filenames.

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>

Here is the error from internal log:

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)

解决方案

I found that all the configuration resides within a app.config for a Unit Test Project as opposed to the NLog.Config file. Be sure to declare the config section and then the NLog configuration. Below is my sample 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和单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆