2

I have an application that needs to redirect the output to Console.Write and Console.Writeline to somewhere else.

To elaborate further, my code starts a process at certain intervals. This proces is not written by me, or the company I work for, and I do not have source-code access. I capture that output from that process because I need to know when I check up on the logs later if something has failed, and stuff like that, so I've redirected the output to a text-file like this:

String filename = "the-log-file-with-a-datetime-stamp.txt";
FileStream filestream = new FileStream(filename, FileMode.Create);
streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);

That works fine, sort of, but I would like to be able to redirect to more than one place, like I know redirect to a streamwriter.

Lets say for arguments sake I want it to redirect to the streamwriter AND write the line in a table in a database, and also show it in console, should someone have manually run the program. How would I go about that?

Can I implement my own TextWriter and handle it there, and if so, how?

Please let me know if I can clarify further.

4

4 回答 4

3

最简单的方法是按照您的建议进行操作并编写您自己的TextWriter派生类。然后,您可以使用它来写入多个其他TextWriter实例。

TextWriter 的文档在其“给继承者的说明”中说:

派生类必须至少实现 TextWriter.Write(Char) 方法才能创建有用的 TextWriter 实例。

所以你的派生TextWriter类看起来像:

public class MultiTextWriter: TextWriter
{
    private List<TextWriter> _writers = new List<TextWriter>();

    public void AddWriter(TextWriter writer)
    {
        _writers.Add(writer);
    }

    public override void Write(char ch)
    {
        foreach (var writer in _writers)
        {
            try
            {
                writer.Write(ch);
            }
            catch (ObjectDisposedException)
            {
                // handle exception here
            }
            catch (IOException)
            {
                // handle exception here
            }
        }
    }
}

并使用它...

MultiTextWriter Writer = new MultiTextWriter();
StreamWriter sw1 = new StreamWriter(...);
StreamWriter sw2 = new StreamWriter(...);
Writer.AddWriter(sw1);
Writer.AddWriter(sw2);

Console.SetOut(Writer);
Console.SetError(Writer);

请注意,我的课程和示例非常少。特别是,您需要添加关闭各个流的代码。而且您必须决定如何处理写入错误。

如果您想获得更好的性能,您可以覆盖其他TextWriter写入方法,但很可能仅覆盖该Write(char)方法就可以很好地执行。这将取决于有多少数据流出以及有多少不同的目的地。

于 2013-06-12T13:41:28.697 回答
0

解决方案示例:编写您自己的派生自 TextWriter 的类,它将输出回显到 StreamWriter 和您的其他地方。

于 2013-06-12T11:19:26.077 回答
0

将输出重定向到 MemoryStream,并对其进行监视(循环+睡眠)。数据到达后,将其发送到您需要的任何地方。

于 2013-06-12T11:12:54.760 回答
0

您可以创建一个从仅支持写入的CompositeStream类派生的类。Stream在覆盖Write方法中,您可以写入任意数量的底层流。

于 2013-06-12T11:18:39.610 回答