Understanding how Trace works in C#

南笙酒味 提交于 2019-12-10 02:06:44

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/11220837/understanding-how-trace-works-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!