How to add (simple) tracing in C#? [closed]

柔情痞子 提交于 2019-11-27 16:42:13

I wrote a short article on using the Trace Listener - maybe it will be of some help, especially for beginners - http://www.daveoncsharp.com/2009/09/create-a-logger-using-the-trace-listener-in-csharp/

I followed around 5 different answers as well as all the blog posts above and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'. For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics config:

  <system.diagnostics>
    <sources>
      <source name="sourceName" switchName="switchName">
        <listeners>
          <add
              name="textWriterTraceListener"
              type="System.Diagnostics.TextWriterTraceListener"
              initializeData="tracelog.txt" />
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="switchName" value="Verbose" />
    </switches>
  </system.diagnostics>

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50, they talk about how to set up the switches in the config file & how to write the code, but it is pretty old (2002). There's another article on CodeProject: http://www.codeproject.com/KB/trace/debugtreatise.aspx but it's the same age. CodeGuru has another article on custom TraceListeners: http://www.codeguru.com/columns/vb/article.php/c5611

I can't think of any more recent articles, hopefully someone else here will have something

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