27 August 2013

Tracing in Asp.Net

Tracing displays the details about how the code was executed. It refers to collecting information about the application while it is running. Tracing information can help you to troubleshoot an application. 
It enables you to record information in various log files about the errors that might occur at run time. 
You can analyze these log files to find the cause of the errors.

In .NET, we have objects called Trace Listeners. A listener is an object that gets the trace output and stores it to different places, 
such as a window, a file on your locale drive, or a SQL Server.

The System.Diagnostics namespace contains the predefined interfaces, classes, and structures that are used for tracing. It supplies two classes, Trace and Debug, which allow you to write errors and logs related to the application execution. Trace listeners are objects that collect the output of tracing processes.
Page level Tracing
ASP.NET tracing can be enabled on a page-by-page basis by adding "Trace=true" to the Page directive in any ASP.NET page:
<%@ Page Language="C#" Trace="true" TraceMode = "SortByCategory"
 Inherits  ="System.Web.UI.Page" CodeFile="Default.aspx.cs" %>
Additionally, you can add the TraceMode attribute that sets SortByCategory or the default, SortByTime. You can use SortByTime to see the methods that take up the most CPU time for your application. You can enable tracing programmatically using the Trace.IsEnabled property.
Application Tracing
You can enable tracing for the entire application by adding tracing settings in web.config. In below example, pageOutput="false" and requestLimit="20" are used,
so trace information is stored for 20 requests, but not displayed on the page because pageOutput attribute is set to false.
<configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <compilation debug="false" />
        <authentication mode="Windows" />
      <trace enabled ="true" pageOutput ="false" requestLimit ="20" traceMode="SortByTime " />        
    </system.web>
</configuration>
The page-level settings take precedence over settings in Web.config,
 so if enabled="false" is set in Web.config but trace="true" is set on the page, tracing occurs.