2016-09-13 19 views
2

私のロガーにNLogを使用しています。 .exeを実行するときにログを記録するとき、またはVisual Studioでデバッグするときにも、NLogはファイルに書き込むことができます。NLogとユニットテスト

しかし、ユニットテストでロガーを呼び出すオブジェクトを実行すると、ファイルは作成されますが空です。ユニットテストの下でNLogにファイルを書き込ませるためにconfigに追加する必要のある追加の設定/ルールがありますか?

私はこのために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

なぜメモリターゲットではなくファイルターゲットにロギングしていますか? – Julian

答えて

1

わからないが、それはかなり確信:ユニットテスト環境からNLog.configを読む

ユニットテストで文字列から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

あなたの返信のために素敵なおかげで!私はこれを試して、あなたに知らせるでしょう。 =)thanks again – TheNoob

+0

私はこの解決策を試しましたが、同じ問題がまだ発生します。あなたの入力のおかげで=)非常に感謝 – TheNoob

+0

あなたはnlogの中でデバッグを回してみましたか、何かが内部nlogファイルに記録されているかどうかを確認しましたか? – Webezine

3

すべての設定は、NLog.Configファイルではなくユニットテストプロジェクトのapp.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>