Trace Listening in ASP.NET Applications

If you are interested in writing your own trace listener (say to write to a database), you can do so from inheriting the System.Diagnostics.TraceListener class, which you can find examples on the web.  However, if you want to use it in your web application, there are several steps you need to take, which you can find documented here:  http://msdn2.microsoft.com/en-us/library/b0ectfxd.aspx

Using this example, you can register custom listeners through:

<system.diagnostics>   
  <trace autoflush="true">
    <listeners>
      <add name="DatabaseTraceListener"
        type="Mains.DatabaseTraceListener, App_Code"/>
    </listeners>
  </trace>
</system.diagnostics> 

Autoflush means messages will be written automatically to the listener; if false, then a manual Flush() method call must be peformed before trace information is written.  You add your custom class using the <add> element, like many other sections in the code.  I left out the initializeData property, which may or may not be allowed with trace listeners.

Once defined, you can use tracing in two ways.  First, you can use it manually:

System.Diagnostics.Trace.Write()

Or you can use the tracing that comes with the Page class (System.Web.TraceContext), defining this in the web.config:

<system.web>
    <trace enabled="true" writeToDiagnosticsTrace="true"/>
</system.web>

writeToDiagnosticsTrace means that all tracing will run through the trace listeners you setup in the <system.diagnostics> section.  The last step is to setup the compilers to output the switch /d:Trace, as defined below:

<system.codedom>
  <compilers>
    <compiler language="c#;cs;csharp"
              extension=".cs"
              compilerOptions="/d:TRACE"
              type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="1" />
    <compiler language="VB"
              extension=".vb"
              compilerOptions="/d:Trace=true"
              type="Microsoft.VisualBasic.VBCodeProvider, System,                                        Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </compilers>
</system.codedom>

For windows projects, you can set up the /d:Trace switch in the property settings for the project.  However, with web applications, you must specify the information here.  If you don't specify the compiler options, tracing information through the diagnostics trace listener is ignored completely, which I found out the hard way when debugging.

Comments

# Catched By .Net - Trace Listening in ASP.NET Applications

Pingback from  Catched By .Net - Trace Listening in ASP.NET Applications

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.