2012-05-14 69 views
1

如果我在Console.Out中看到一些關鍵字,我想退出該程序。這是因爲我們使用的第三方DLL有一個問題,即遇到某種特殊的異常時它永遠不會退出。如何監視console.out?

對我們唯一的好處似乎是監視回填到console.Out的日誌。並根據console.out的日誌,主機應用程序可以決定遇到此類異常時應如何處理。

有人告訴我,我可以使用跟蹤偵聽器......但我不確定這一點。 你們認爲什麼?

回答

3

Console類提供了SetOut方法,該方法可用於將輸出寫入自定義流。例如,您可以流式傳輸到一個StringBuilder並監視變化,或者編寫一個自定義流實現來監視關鍵字。

例如,這裏是一個KeywordWatcherStreamWrapper類,手錶指定的關鍵字,並提出只要關鍵字被視爲對所有聽衆的事件:

public class KeywordWatcherStreamWrapper : TextWriter 
{ 
    private TextWriter underlyingStream; 
    private string keyword; 
    public event EventHandler KeywordFound; 
    public KeywordWatcherStreamWrapper(TextWriter underlyingStream, string keyword) 
    { 
     this.underlyingStream = underlyingStream; 
     this.keyword = keyword; 
    } 

    public override Encoding Encoding 
    { 
     get { return this.underlyingStream.Encoding; } 
    } 

    public override void Write(string s) 
    { 
     this.underlyingStream.Write(s); 
     if (s.Contains(keyword)) 
      if (KeywordFound != null) 
       KeywordFound(this, EventArgs.Empty); 
    } 

    public override void WriteLine(string s) 
    { 
     this.underlyingStream.WriteLine(s); 
     if (s.Contains(keyword)) 
      if (KeywordFound != null) 
       KeywordFound(this, EventArgs.Empty); 
    } 
} 

使用範例:

var kw = new KeywordWatcherStreamWrapper(Console.Out, "Hello"); 
kw.KeywordFound += (s, e) => { throw new Exception("Keyword found!"); }; 

try { 
    Console.SetOut(kw); 
    Console.WriteLine("Testing"); 
    Console.WriteLine("Hel"); 
    Console.WriteLine("lo"); 
    Console.WriteLine("Hello"); 
    Console.WriteLine("Final"); 
} catch (Exception ex) { Console.Write(ex.Message); } 

在第二個Write聲明包含整個關鍵字,則會引發該事件,從而引發異常。還要注意,這會默默地包裝底層流並仍然寫入,所以控制檯輸出仍然正常生成。

輸出示例:

Testing 
Hel 
lo 
Hello 
Keyword found! 
+0

非常感謝。它只對我有一部分作用。一些在控制檯中使用的日誌不會被KeywordWatcherStreamWrapper過濾掉。不知道是什麼原因 – KKKoo0

+0

我只重寫了'TextWriter'類的兩個方法:'Write(string)'和'WriteLine(string)'。有30-40種可能的方法可以覆蓋,因此您可能需要檢查是否正在使用其他方法,例如'WriteLine(object)'或'WriteLine(bool)'等。 – mellamokb

+0

yes,true ,那肯定是問題所在。我使用另一種方法來解決這個問題,通過使用跟蹤監聽器 – KKKoo0

0

,如果你能包裝成一個EXE這一點,也許你可以使用Process.StandardOutput。

+0

我想這樣做的過程中 – KKKoo0