Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how Trace works in C#

Tags:

c#

trace

I am trying to understand how does Tracing works

I have created a simple new web project. This is my code that I can using

// Create a trace listener for the event log.
EventLogTraceListener myTraceListener = new EventLogTraceListener("myEventLogSource");

// Add the event log trace listener to the collection.
Trace.Listeners.Add(myTraceListener);

// Write output to the event log.
Trace.WriteLine("Test output");

I am taking help from this msdn link

The settings in my web.config is as follows

 <system.diagnostics>
 <trace autoflush="false" indentsize="4">
  <listeners>
    <add name="myListener"
      type="System.Diagnostics.EventLogTraceListener"
      initializeData="TraceListenerLog" />
  </listeners>
 </trace>
</system.diagnostics>

However when I run this code, I dont know where this logging is happening I check the EVENT VIEWER, under the "Application and Services Log" I was expecting some new log to be created with the name "myEventLogSource" but that has not happened.

Please can anyone explain me how this works.

like image 256
Yasser Shaikh Avatar asked Jun 27 '12 06:06

Yasser Shaikh


1 Answers

Under the Application log check if you have two Sources that were writting to the Application log, one is TraceListenerLog and the other one is myEventLogSource. New log is not going to be created, they will both use Application log. If you want to create a new log and you want to write trace output to it, you can do it like this (of course, log name doesn't have to be equal to source name):

        string logSource = "_myEventLogSource";
        if (!EventLog.SourceExists(logSource))
            EventLog.CreateEventSource(logSource, logSource);

        EventLogTraceListener myTraceListener = new EventLogTraceListener(logSource);

        // Add the event log trace listener to the collection.
        System.Diagnostics.Trace.Listeners.Add(myTraceListener);

        // Write output to the event log.
        System.Diagnostics.Trace.WriteLine("Test output");

Even if the source wouldn't exist, trace information would get written to the event log under the Application log with a source name you have passed to the EventLogTraceListener constructor.

like image 60
Ivan Golović Avatar answered Oct 05 '22 16:10

Ivan Golović