2012-05-14 6 views
1

Console.Out에 몇 가지 핵심 단어가 표시되면 프로그램을 종료하고 싶습니다. 우리가 제 3 자 DLL을 사용하기 때문에 이것은 특정 예외가 발생하지 않을 때 종료되지 않는 문제가 있기 때문입니다.console.out을 어떻게 모니터 할 수 있습니까?

우리에게 유일한 슬픔은 console.Out으로 다시 채워진 로그를 모니터링하는 것 같습니다. console.out의 로그를 기반으로 호스트 응용 프로그램은 이러한 예외가 발생할 때 수행 할 작업을 결정할 수 있습니다.

누군가 내가 트레이스 리스너를 사용할 수 있다고 말했지만, 확실하지 않습니다. 너희들은 어떻게 생각하니?

답변

3

Console 클래스는 출력을 사용자 정의 스트림에 쓰는 데 사용할 수있는 SetOut 메서드를 제공합니다. 예를 들어 StringBuilder로 스트리밍하고 변경 사항을 모니터링하거나 키워드를 감시하는 사용자 정의 스트림 구현을 작성할 수 있습니다. 예를 들어

, 여기에 지정된 키워드를 감시하는 KeywordWatcherStreamWrapper 클래스이며, 키워드가 볼 때마다 모든 리스너에 대한 이벤트 발생합니다 다음에

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); } 

:

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); 
    } 
} 

샘플 사용을 전체 키워드를 포함하는 두 번째 Write 문은 이벤트가 발생하고 예외가 발생합니다. 또한 기본 스트림을 자동으로 래핑하고 여전히 기록하므로 콘솔 출력은 여전히 ​​정상적으로 생성됩니다.

샘플 출력은 : 당신이 EXE에이를 포장 할 수있는 경우

Testing 
Hel 
lo 
Hello 
Keyword found! 
+0

감사합니다. 그것은 나를 위해 부분적으로 만 작용합니다. 콘솔에서 apprearing하는 로그 중 일부는 KeywordWatcherStreamWrapper에 의해 필터링되지 않습니다. 이유가 무엇인지 모르겠습니다. – KKKoo0

+0

'Write (string)'과'WriteLine (string)'의 두가지 메소드 인'TextWriter'를 오버라이드했습니다. 무시할 수있는 방법은 30-40 가지가 있습니다. 예를 들어'WriteLine (object)'또는'WriteLine (bool)'등과 같이 다른 것들이 사용되고 있는지 확인해야 할 수도 있습니다. – mellamokb

+0

예, true 그것은 문제가되어야합니다. 추적 수신기를 사용하여이 문제를 해결하는 또 다른 방법을 사용했습니다. – KKKoo0

0

, 어쩌면 당신은 Process.StandardOutput를 사용할 수 있습니다.

+0

이 과정에서이 작업을 수행하려고합니다. – KKKoo0

관련 문제