繁体   English   中英

如何监控console.out?

[英]How can I monitor console.out?

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

唯一sulotion我们似乎被监视填充回日志console.Out 并且基于登录console.out ,主机应用程序可以在遇到此类异常时确定要执行的操作。

有人告诉我,我可以使用跟踪侦听器...但我不确定。 你们有什么感想?

Console类提供了SetOut方法,可用于将输出写入自定义流。 例如,您可以流式传输到StringBuilder并监视更改,或者编写一个监视关键字的自定义流实现。

例如,这是一个KeywordWatcherStreamWrapper类,它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!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM