0

I would like to be able to log all console output from my application into a text file. I've implemented a ConsoleTraceListener and TextWriterTraceListener as described in the following post: Mirroring console output to a file

This works well for all normal console output. However, I would also like for the StdError stream to show up in the log file. I tested with some simple code that eventually throws a DivideByZeroException (code shown below). With the implementation suggested in the above post, the error message shows up in the console but not in the log file.

Does anyone have suggestions for how to this can be achieved? Please note I'm not looking to redirect the Stderror stream. Ideally, the error message will show up in both the console and the log file.

Thanks in advance for any suggestions!

Trace.Listeners.Clear();
string logfilePath = @"Q:\logfile.txt";
TextWriterTraceListener log_tracer = new TextWriterTraceListener(logfilePath);
log_tracer.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime;
ConsoleTraceListener console_tracer = new ConsoleTraceListener(false);
console_tracer.TraceOutputOptions = TraceOptions.DateTime;
Trace.Listeners.Add(log_tracer);
Trace.Listeners.Add(console_tracer);
Trace.AutoFlush = true;

Trace.WriteLine("HELLO THIS IS TO TEST THE TRACE LISTENER");
for (int a = 5; a >= 0; a--) {
    Trace.WriteLine(50 / a);
}
Community
  • 1
  • 1
lisa
  • 43
  • 4

1 Answers1

0

For the benefit of anyone with the same question, here's how I ended up working my way around the problem:

I basically implemented an exception handler and placed the Trace.WriteLine() inside of the catch part of the code. For example:

try {
    // Code that can potentially create StdError message
}
catch (Exception ex) {
    Trace.WriteLine(ex.ToString());
}

Hope that helps, in case anyone had the same problem!

lisa
  • 43
  • 4