开发者

Duplicate console output of self process

I'd like to redirect my process console output to file, while mantaining the utility of displaying it on the curretnly attached console.

The redirection is done easily with:

using (FileStream fs = new FileStream(TestLogName("Texture"), FileMode.Create, FileAccess.Write)) {
    Console.Se开发者_JAVA技巧tOut(new StreamWriter(fs));

    ...

    Console.Out.Flush();
}

But how I can achieve the same result while mantaining the console output on already attached console (de-facto duplicating the stream)?


You can sub-class TextWriter with a class that writes to a file and another TextWriter class. Then initialize an instance of this class with the current value of System.Console.Out.

var writer = new SplitWriter(Console.Out, @"c:\temp\logfile.txt");
Console.SetOut(writer);

SplitWriter then takes responsibility for writing to both the file and the original value of Console.Out.


You can attach the Console and a log file as Trace listeners, and replace all usages of Console writing methods with Trace:

Trace.Listeners.Add(new ConsoleTraceListener());
Trace.Listeners.Add(new DefaultTraceListener{LogFileName="C:\temp\myOutput.txt"});

...       

Trace.Flush();
Trace.Listeners.Clear();

Understand that Trace, unlike Console, cannot be read from, so if you ever use Console.ReadLine and want to record the user's input, you'll need to "echo" it back to the trace listeners.

If you wanted to go a little more SOLID, you could set up an IOutputWriter interface, then implement three classes; one that writes to the console, one that writes to a file, and a third that has a collection of other IOutputWriters and routes any call to its methods to all of the attached IOutputWriters. This uses the Composite and Adapter patterns to normalize the interface between your program and anything listening to it. This sidesteps the built-in Trace/Debug functionality, but if you're already using that for a different level of messaging, or you need your messaging to work a little differently than the default provided by Trace, this is to go-to alternate.


I think you'll have to call WinAPI functions like WriteConsoleOutput. I see no perspective of forwarding every other write in multi-threaded environment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜