4

I want to make calls like the following in my code:

System.Diagnostics.Trace.WriteLine("Starting XYZ...");

and write it to a file as described in the config:

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

This works great, apart from the fact there are existing calls to WriteLine() that are currently getting mixed up with the new lines of code I've added.

How can I write my trace to one log file and leave the existing ones as they are (currently no config at all before I amended it, I'd like the existing trace to be handled as it currently is).

I know this is achievable through code, but I'd like to specify the file in the config file and conditionally write to it.

2 Answers2

2

Just understood what your question was asking. Edited my comment. You can use trace sources like in the following: http://olondono.blogspot.com/2008/01/about-trace-listeners.html

Basically you can modify your config file like this:

    <system.diagnostics>
        <trace autoflush="true"/>
          <sources>
            <source name="myTraceSource"
              switchName="mySwitch"
              switchType="System.Diagnostics.SourceSwitch" >
           <listeners>
            <clear/>
            <add name="textwriterListener"
             type="System.Diagnostics.TextWriterTraceListener"
             initializeData="c:\myLog.txt" />
           </listeners>
         </source>
     </sources>
     <switches>
       <add name="mySwitch" value="Warning" />
     </switches>
   </system.diagnostics>

Then in your code you can do the following:

    // First step: create the trace source object
    TraceSource ts = new TraceSource("myTraceSource");

    // Writing out some events
    ts.TraceEvent(TraceEventType.Warning, 0, "warning message");
    ts.TraceEvent(TraceEventType.Error, 0, "error message");
    ts.TraceEvent(TraceEventType.Information, 0, "information message");
    ts.TraceEvent(TraceEventType.Critical, 0, "critical message");
The Mahahaj
  • 696
  • 6
  • 8
1

You want to use TraceSource this allows your app to write to traceForStartUp, traceForPerfomance, joesTrace, legacyTraceThatIDontWantToCommentout and then turn them on or off depending on what sort of trace you're interested in.

http://msdn.microsoft.com/en-us/library/ms228993%28v=vs.110%29.aspx

You can further filter a trace source, (i.e. send trace to the log from 9-5, but have a different trace listener send trace to an email listener after hours) But I don't think that is what you are looking for, it just happens to be the name of a class in this namespace.

MatthewMartin
  • 32,326
  • 33
  • 105
  • 164