Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

vb.net - Overriding System.Diagnostics.Trace.WriteLine to log to a file

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.WriteLine so it can be viewed with DebugView.

I'd like to override/extend (not sure of the proper terminology) this method to log the text to a file instead, or maybe in addition to the Trace output. This would allow me to write a new WriteLine method for my app, and I could leave all my other System.Diagnostics.Trace.WriteLine statements unchanged throughout the rest of the application.

So how would I go about changing the behavior of this method within my VB.Net app?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...