Overriding System.Diagnostics.Trace.WriteLine to log to a file

前端 未结 2 513
孤城傲影
孤城傲影 2020-12-13 16:07

This may be more of an OOP concept question, but here\'s what I\'d like to do.

I have an application that outputs debug information using System.Diagnostics.Trace.Wr

相关标签:
2条回答
  • 2020-12-13 16:35

    Are you absolutely committed to still using Trace? If not, I'd use a more fully-featured logging system such as Log4Net.

    However, if you really want to use Trace then you can reconfigure the TraceListeners used with an app.config file. The TraceListener MSDN docs give an example somewhat like this:

    <configuration>
      <system.diagnostics>
        <trace autoflush="false" indentsize="4">
          <listeners>
            <add name="fileLogger" 
                 type="System.Diagnostics.TextWriterTraceListener" 
                 initializeData="LogFile.log" />
            <remove name="Default" />
          </listeners>
        </trace>
      </system.diagnostics>
    </configuration>
    

    TextWriterTraceListener will dump logs to the given file. (There are other options available too.)

    Alternatively, you can do this programmatically:

    Trace.Listeners.Add(new TextWriterTraceListener("foo.log"));
    

    Note that you may need to explicitly flush the traces before your app exits, either with:

    Trace.Flush();
    

    or the more complicated:

    foreach (TraceListener listener in Trace.Listeners)
    {
        listener.Flush();
    }
    

    (I only mention it because I had to when testing this!)

    EDIT: As noted in comments, if you're happy for the listener to be flushed after every write (which avoids having to flush at the end, but may harm performance) you can set Trace.AutoFlush to true (including in the XML - see the autoflush attribute).

    0 讨论(0)
  • 2020-12-13 16:39

    There is a TextWriterTraceListener which you can configure to output the trace log to a file. Configuration information can be found on the MSDN here:

    http://msdn.microsoft.com/en-us/library/system.diagnostics.textwritertracelistener(VS.80).aspx

    You can also dump to the event log or a variety of other places for a list of built in trace listeners you can look here:

    http://msdn.microsoft.com/en-us/library/4y5y10s7(VS.80).aspx

    0 讨论(0)
提交回复
热议问题