2014-01-07 53 views
0

我從Main()直接登錄時創建了一個控制檯應用程序,可以成功記錄消息。我希望做的是設置一個處理程序來處理所有未處理的異常:NLog - 綁定到UnhandledExceptionEventHandler時遇到困難日誌記錄

class Program 
    { 
     private static Logger logger = LogManager.GetCurrentClassLogger(); 
     static void Main(string[] args) 
     { 
      AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); 
      throw new ApplicationException("Throwing an unhandled exception!"); //This line keeps getting hit 
      Console.ReadLine(); 
     } 

     private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
     { 
      var exc = (Exception)e.ExceptionObject; 
      logger.ErrorException("Another exception occured!", exc); 
     } 
    } 

此應用程序從不卸載,我試圖找出原因。它會拋出我的ApplicationException,然後執行CurrentDomain_UnhandledException(),但隨後調試器返回到行:throw new ApplicationException()。再次執行CurrentDomain_UnhandledException(),然後我回到將異常投入無限遠和更遠的行。

即使調用了logger.ErrorException(),也沒有任何內容寫入數據庫。

回答

1

對於第一部分,當您正常運行時會發生什麼情況?

我懷疑是因爲你在調試的時候調試器解開了調用堆棧,因此你最終回到拋出異常的地方,所以持續不斷的繼續不會讓你感覺到任何地方。

我相信有一個選項可以防止這種行爲,請參閱Tools >> Options >> Debugging >> General

但是,我會保留它並接受此爲預期行爲(只要在調試之外正確處理未處理的異常)。

enter image description here

至於第二部分,對我不確定它可能是你使用的只是沒有得到機會去刷新,無論附加器。我會切換到文件,看看它是否記錄在那裏檢查。