2015-06-29 29 views
1

我正在通過NUnit運行測試並希望讓NLog消息快速告訴我對每條日誌消息的調用測試。像添加調用NUnit測試到NLog輸出

<target xsi:type="File" 
      layout="${longdate} ${someMagic} ${message}" 
      /> 

有沒有一種簡單的方法來做到這一點,而不會深入到NLog代碼中?

回答

1

這裏是一個有效的解決方案:一組擴展方法包裝NLOG ILogger.Error(..)方法和喜歡,查找堆棧的NUnit的[Test][TestCase]屬性

public static void XError(this ILogger log, String message) 
    { 
     if (log.IsErrorEnabled == false) 
      return; 

     var prefix = GetCallerTestDescription(); 
     log.Error("[{0}] {1}", prefix, message); 
    } 

    private static string GetCallerTestDescription() 
    { 
     var stack = new StackTrace(false).GetFrames(); 

     if (stack != null) 
     { 
      foreach (var frame in stack) 
      { 
       var method = frame.GetMethod(); 
       var testAttributes = method.GetCustomAttributes<TestAttribute>(); 

       if (testAttributes != null && testAttributes.Any()) 
       { 
        return method.Name; 
       } 

       var tcAttributes = method.GetCustomAttributes<TestCaseAttribute>(); 
       if (tcAttributes != null && tcAttributes.Any()) 
       { 
        return method.Name; 
       } 

      } 
     }