Hans Rudel Hans Rudel - 1 year ago 73
C# Question

Turning trace on and off, and specifying filepath at runtime

I am curious about the following:

<?xml version="1.0" encoding="utf-8" ?>
<trace autoflush="false" indentsize="4">
<add name="logger" type="System.Diagnostics.TextWriterTraceListener"
initializeData="LoggingFile.txt" />
<remove name="Default" />

I want to include the option in my solution to log error messages and the stack trace. But I need to be able to turn this on and off. Is this possible by commenting out everything in
? Or is there a better way?

Is it possible to specify what file the logger writes to at run-time?

Answer Source

You can make use of a SourceSwitch which allows you to trace different levels of messages. First start by adding some settings to app.config

    <source name="TraceTest" switchName="SourceSwitch"
            <!-- choose one or use multiple TraceListeners -->
            <add name="console" type="System.Diagnostics.ConsoleTraceListener"
            <add name="file" type="System.Diagnostics.TextWriterTraceListener"
            <remove name ="Default"/>
    <!--  MSDN: 4 verbose Information, Information 3, Warning 2, Error 1, -->
    <add name="SourceSwitch" value="Error"/>
  <trace autoflush="true" indentsize="4"/>

Within your application you can trace messages by using a TraceSource object referring to the definied name within app.config

TraceSource ts = new TraceSource("TraceTest");
ts.TraceEvent(TraceEventType.Information, 123, "event info");
ts.TraceEvent(TraceEventType.Error, 123, "event error");
ts.TraceEvent(TraceEventType.Warning, 123, "event warning");

ts.TraceInformation("any text");

For some common information have a look at How to: Use TraceSource ... at MSDN. Using Dr. Google I found an related question at SO referring to a very good blogpost concerning this matter.

One thing I'd like to point out ...

To change the level at which a listener writes a trace message

The configuration file initializes the settings for the trace source at the time the application is initialized. To change those settings you must change the configuration file and restart the application or programmatically refresh the application using the TraceRefresh method. The application can dynamically change the properties set by the configuration file to override any settings specified by the user. For example, you might want to assure that critical messages are always sent to a text file, regardless of the current configuration settings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download