如何监控console.out?

时间:2012-05-14 22:19:16

标签: c# stream console tracelistener

如果我在Console.Out中看到一些关键词,我想退出该计划。这是因为我们使用第三方DLL,它遇到一个问题,当它遇到一些特殊的异常时它永远不会退出。

对我们的唯一不满似乎是监视填充回console.Out的日志。根据登录console.out,主机应用程序可以在遇到此类异常时确定要执行的操作。

有人告诉我,我可以使用跟踪侦听器...但我不确定。 你觉得怎么样?

2 个答案:

答案 0 :(得分: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!

答案 1 :(得分:0)

如果你可以将它包装到exe中,也许你可以使用Process.StandardOutput。