Click here to Skip to main content
15,867,756 members
Articles / Web Development / ASP.NET

Step by Step Guide to Trace the ASP.NET Application for Beginners

Rate me:
Please Sign up or sign in to vote.
4.54/5 (23 votes)
19 May 2010CPOL5 min read 158.5K   2.2K   52   11
Explains the step by step approach to trace the ASP.NET application

Introduction

I am new to ASP.NET and while learning Tracing, I found that there are few resources available for the tracing for beginners which should cover important topics. I searched CodeProject, but was not able to get a good start up tutorial, so I decided to write the tutorial for beginners.

Contents

  • Types of Tracing
  • Writing Custom Trace Information
  • Page.Trace Vs System.Diagnostics.Trace
  • Integrate System.Diagnostics with ASPX Page (Routing all Trace information to web page)
  • trace.axd file
  • Creating Custom Trace Listeners
  • Saving Trace information in File

Types of Tracing

In ASP.NET, there two types of Tracing:

  • Application Level
  • Page Level

Page level tracing takes precedence over Application level tracing.

Let's start with creating a new website.

In web.config, add the following entries to enable Application level tracing below System.web element.

XML
 <trace pageOutput="true"
enabled="true"
requestLimit="10"
localOnly="false"
mostRecent="true"
traceMode="SortByTime"
/> 

where:

  • pageOutput=”true” – Add the tracing information at the bottom of the ASPX page.
  • localOnly=”false” – Tracing will be available to any web page.
  • requestLimit=”10? – How many requests should be saved on the server.
  • mostRecent=”true” - Whether or not to display the recent tracing information if the request reached the limit.

After adding the above tag in web.config, simply run the Default.aspx page and the output of ASP.NET page will look like:

Here you can see much of the information displayed like SessionId, Request Status, Controls available on that page. All the events of the page with start and end time, etc. and thus you can figure out the performance of your web application.

No Trace for a Particular Page

Create a web page and in aspx file at header, write the tag Trace=”false”.

Create a few controls like link button and view the page in browser. You will see that the page is displayed with no tracing information, although its turned ON in web.config because page level tracing has the precedence over application level tracing.

Writing Custom Trace Information

Now on the click event of Link buttons, write the custom trace information.

C#
protected void lblwriteMessage_Click(object sender, EventArgs e){
Trace.Write("Custome Message", "Write Link Button clicked");
}
protected void lblwarnMessage_Click(object sender, EventArgs e)
{
Trace.Warn("Custome Message", "Warn Link Button clicked");
}  

when you will click on the WriteLink button, the below output will be seen:

And when you will click on warn button, the message will be displayed in Red color. So it is suggested to display the important trace message as a warning.

Page.Trace Vs System.Diagnostics.Trace

Create a new class file and write a static function which will write the Trace Message. You will notice that Trace object is not available by default like ASPX page instead you will need to import the package “System.Diagnostics”.

So, there is a lot difference in System.Diagnostic.Trace and Page.Trace.

Trace from Diagnostics display the trace information in output window of Visual Studio whereas the Trace from page displays the Trace information in ASPX Page.

Integrate System.Diagnostics with ASPX Page (Routing all Trace information to web page)

We will need to add the listener in web.config file to route all the tracing information to the single web page.

To integrate the System.Diagnostics Trace with ASPX page, write the below line of code in web.config.

XML
  <system.diagnostics> 
  <trace> 
    <listeners>
       <add name="WebPageTraceListener"
            type="System.Web.WebPageTraceListener, System.Web, 
	   Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    </listeners>
  </trace>
</system.diagnostics> 

The output will look like the below image:

trace.axd File

This file contains all the information about the tracing of the application.

To view the trace information, just write the file name and you will get page which will look like the below snap.

Path structure: http://<servername>/webapp/trace.axd

Creating Custom Trace Listeners

Database Trace Listener

.NET has provided us the flexibility of writing our own Trace Listeners in the form of the TraceListener class. Every Trace Listener is inherited from this class; therefore, in order to implement your own Trace Listener, you must inherit your Trace Listener class from this class.

All Trace Listeners have the following functions. Functionality of these functions is the same except that the target media for the tracing output is determined by the Trace Listener.

Method Name Result
Fail Outputs the specified text with the Call Stack.
Write Outputs the specified text.
WriteLine Outputs the specified text and a carriage return.
Flush Flushes the output buffer to the target media.
Close Closes the output stream in order not to receive the tracing/debugging output.

TraceListener class has many virtual and abstract methods; at the very least, each inheritor of this class must implement the Write and WriteLine methods; other important methods are Fail, Close, and Flush. Inheritors are not supposed to implement these methods but it is a good idea to implement these methods. Descriptions of these methods are given in the beginning of the article.

Write and WriteLine methods are overloaded; following is a list of all the overloaded version of the Write method:

  • C#
    public override void Write(string message)
  • C#
    public override void Write(object o)
  • C#
    public override void Write(object o, string category)
  • C#
    public override void Write(string message, string category)

For this article, I have created a Trace Listener, DatabaseTraceListener, which actually stores trace and debug messages into a database.

Add the below code in Web.config which stores the connection string information.

XML
<appSettings> <add key="ConnectionString" 
value="Data Source=.\SQLExpress;Integrated Security=True;
User Instance=True;AttachDBFilename=|DataDirectory|TraceDB.mdf" />
<add key="MaximumRequests" value="2" /> </appSettings>  

The structure of table is as follows:

  • TraceDateTime column stores the date and time of the trace message
  • TraceCategory column stores the actual category of the trace message
  • TraceDescription column stores the trace message
  • StackTrace column contains the stack trace
  • DetailedErrorDescription column contains the detailed error message which will be passed in second parameter of the Fail method

Create Below Stored Procedure

SQL
CREATE procedure usp_AddTrace 
@r_dtTraceDateTime	datetime,
@r_vcTraceCategory	varchar(50),
@r_vcTraceDescription	varchar(1024),
@r_vcStackTrace		varchar(2048),
@r_vcDetailedErrorDescription	varchar(2048)
as 
begin 
insert
Traces 	(TraceDateTime, TraceCategory, TraceDescription, 
	StackTrace, DetailedErrorDescription) 
values 
(@r_dtTraceDateTime, @r_vcTraceCategory, @r_vcTraceDescription, 
	@r_vcStackTrace, @r_vcDetailedErrorDescription) 
return @@error
end 

Now create a class named “DatabaseTraceListener” which inherits the abstract class “TraceListener”. You can check the code snippets in the source code of this article.

If you want to implement your own Trace Listener, simply derive your listener class from TraceListener class, implement at least the Write and WriteLine methods and you are done.

In our Example, Flush and Close methods simply save all the cached messages into the database.

Saving Trace information in File

We can also save the trace information in log files.

To save the trace information in File, simply add the following entry in web.config.

XML
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" 
initializeData="TextWriterOutput.log" />  

For Readers

I tried to put maximum topics related to Tracing of ASP.NET application, but please point out if I missed any important concept / topic. I hope this will help a few new developers who want to learn tracing in ASP.NET.

History

  • 19th May, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Cognizant Technology Solutions
India India
Having more than 9 years of experience in Programming and web application development.

Writing technical blog articles, learning new Programming languages , frameworks and sharing knowledge with others is one of my hobby. The more I learn, more I understood that how little I know and that drives me to dig into technology and languages to explore.

From last few years now, working on Salesforce platform and providing customer solutions using force.com as an Architect and Technical Lead Role. I have worked on many area of Salesforce like force.com, Heroku, PHP Toolkit, Partner Webservices, Metadata and Enterprise webservices, Tooling API, Customer Portal, Partner Portal, Community, Salesforce1 etc...

Blog:http://www.jitendrazaa.com/blog

Comments and Discussions

 
GeneralMy vote of 1 Pin
ashwini37374-Aug-14 19:39
ashwini37374-Aug-14 19:39 
GeneralRe: My vote of 1 Pin
Pete O'Hanlon4-Aug-14 23:21
subeditorPete O'Hanlon4-Aug-14 23:21 
GeneralMy vote of 5 Pin
Moumit Mondal4-Jun-14 23:36
Moumit Mondal4-Jun-14 23:36 
QuestionStore server variables and event tracking in database using TraceListener. Pin
amit286218-Apr-14 18:11
amit286218-Apr-14 18:11 
Questionlog Server Variables in database using tracing Pin
amit286215-Apr-14 23:44
amit286215-Apr-14 23:44 
QuestionGreat Article. My Vote of 5! Pin
Ramya Narayanan26-Oct-11 4:50
Ramya Narayanan26-Oct-11 4:50 
Questionaspx page trace to db Pin
deostroll18-Aug-11 0:06
deostroll18-Aug-11 0:06 
GeneralNeed to compile it Pin
awgtek30-Jun-10 10:52
awgtek30-Jun-10 10:52 
GeneralVery nice article Pin
Tushar Bhatt20-May-10 19:03
Tushar Bhatt20-May-10 19:03 
Really good explanation of asp.net tracing. Very Helpful.
QuestionMissing Images? Pin
Yusuf20-May-10 8:57
Yusuf20-May-10 8:57 
AnswerRe: Missing Images? Pin
Jitendra Zaa20-May-10 19:02
Jitendra Zaa20-May-10 19:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.