Writing C# debug output to .txt file

2020-02-08 07:43发布

I'm running code on a microcontroller with .NET Micro Framework, and I want my debug output to write to a text file. How does this work?

4条回答
淡お忘
2楼-- · 2020-02-08 08:19

The most flexible solution for using a out-of-the-box tracing is to make an application configuration file that will define trace listeners.

<configuration>
  <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add name="textListener" 
             type="System.Diagnostics.TextWriterTraceListener" 
             initializeData="trace.log" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

Then, in your application, whenever you want to log something, just do:

Trace.WriteLine("Hello, this is a trace");

But the power of the TraceListener class lies into its granularity. You can chose between Error, Info and Warning levels and define different log file for whatever level you need to trace. Using configuration files makes it also easier to disable tracing in your application because you don't need to recompile your application.

For more informations on tracing system, check this MSDN article.

查看更多
【Aperson】
3楼-- · 2020-02-08 08:32

Use Trace. It is designed to do what you need.

using System;
using System.Diagnostics;

class Test
{
    static void Main()
    {
       Trace.Listeners.Add(new TextWriterTraceListener("yourlog.log"));
       Trace.AutoFlush = true;
       Trace.Indent();
       Trace.WriteLine("Entering Main");
       Console.WriteLine("Hello World.");
       Trace.WriteLine("Exiting Main");
       Trace.Unindent();
       Trace.Flush();
    }
}
查看更多
在下西门庆
4楼-- · 2020-02-08 08:40

Ekk is right about Trace being a better design, however that doesn't answer the question, which would be fine in the absence of a direct solution. The OP or someone may have inherited a code base which uses Debug throughout, and Trace may not be desirable at the time.

I found this solution [http://bytes.com/topic/c-sharp/answers/273066-redirect-output-debug-writeline] :

TextWriterTraceListener[] listeners = new TextWriterTraceListener[] {
new TextWriterTraceListener("C:\\debug.txt"),
new TextWriterTraceListener(Console.Out)
};

Debug.Listeners.AddRange(listeners);

Debug.WriteLine("Some Value", "Some Category");
Debug.WriteLine("Some Other Value");
查看更多
在下西门庆
5楼-- · 2020-02-08 08:40

You will have to do something like this:

// Set up listener
string filename = @"C:\listener.txt";
FileStream traceLog = new FileStream(filename, FileMode.OpenOrCreate);
TextWriterTraceListener listener = new TextWriterTraceListener(traceLog);

// Output to listener
listener.WriteLine("Trace message here");

// Flush any open output before termination.
// Maybe in an override of Form.OnClosed.
listener.Flush();

Taken from here.

Another related question

查看更多
登录 后发表回答