Tracing and loging in Asp.Net MVC

Tracing and loging in Asp.Net MVC 4, discussing on TraceMethods, levels and TraceListeners.

 Asp.Net   
 

Posted: May 19, 2017. | By: mustafa

In this article we are going to discuss how to integrate ASP.NET tracing with System.Diagnostics class and write all trace messages to a single tracing output.
 
With the help of tracing, you can examine HTTP request, view state, and other useful profiling information.  It helps track the flow of execution & also display data at some critical points.
 
 
Let us start by adding web.config adding trace option enabled true by default it is false.
 
<system.web>
    <trace enabled="true" pageOutput="true" requestLimit="40" traceMode="SortByTime" localOnly="false"
    writeToDiagnosticsTrace="true"/>
</system.web>

Note: pageOutput="true" will give trace information on the page in browser window. To disable set  pageOutput to false but we can still see the trace information using the web path: http://localhost:[port]/Trace.axd.
 
We always require to log trace information in some log file or event viewer so that later we can see what error has occurred.
 
We need to enable the writetoDiagnosticsTrace attribute to true. When this attribute is set to true the information is sent to a listener.
 
Other trace attributes are:
  • enabled – Set true to enable tracing, by defaylt it is false.
  • PageOutput - This attribute should be true if we want to display tracing information on both the tracing pages and in trace.axd file, otherwise false. The default is false.
  • RequestLimit – Maximum number of request Asp.Net will store for tracing, default is 10.
  • traceMode – it has following values: SortByTime and SortByCategory. The default is SortByTime.
  • LocalOnly - This attribute specifies whether the trace.axd file is accessible from the local server only (true) or it can be accessed from  remote, default value is true.
 
You can then define various types of listeners like text file listener, event viewer etc. Below is a sample configuration adding TextWriterTraceListener.
 
<system.diagnostics>
<trace autoflush="true">
<listeners>
<clear/>
<add name="textwriterListener" type="System.Diagnostics.TextWriterTraceListener" 
  initializeData="TraceLog\outfile.txt" traceOutputOptions="ProcessId, DateTime"/>
</listeners>
</trace>
</system.diagnostics>
 
Note: we have set autoflush true to allow trace listeners to write to output as it receives any trace message.
 
The System.Diagnostics namespace provides two classes named Trace and Debug that are used for writing errors and application execution information in logs.
 
By default, Visual Studio .NET defines both DEBUG and TRACE for Debug (development) configurations and only TRACE for Release (production) configurations. 

To start writing trace messages use system.diagnostics trace class in code.
 
System.Diagnostics.Trace.Write("Calling Index method of HomeController class");
 
This is a quick example of how to add trace listeners in Asp.Net MVC 4 and write trace logs. Now let us discuss what are Trace Switches, Trace Methods and Trace Listeners in detail.
 
TraceSwitches
There are two types of trace switches: BooleanSwitch and TraceSwitch.
 
Boolean switch has its value is 0 or 1, will write all or nothing. When all tracing is turned on, the output can quickly use a lot of resources is good when your application is small.
 
<switches>
         <add name="BooleanSwitch" value="1" />
   </switches>

How to consume boolean switch using code
BooleanSwitch boolSwitch = new BooleanSwitch(
            "BooleanSwitch",
            "Boolean Switch");

Trace.WriteLineIf(
                  boolSwitch.Enabled,
                  "Testing Boolean Switch.",
                  boolSwitch.Description);
 
TraceSwitch
In production we always want to diagnose a problem and trace and gather information at different level depending on our requirements.
 

The TraceSwitch has five different trace levels defined with their corresponding enum value: Off (0), Error (1), Warning (2), Info (3), and Verbose (4).

  • Off - Outputs no messages to Trace Listeners
  • Error - Outputs only error messages to Trace Listeners
  • Warning - Outputs error and warning messages to Trace Listeners
  • Info - Outputs informational, warning and error messages to Trace Listeners. We generally use enter and exit methods.
  • Verbose - Outputs all messages to Trace Listeners
 
Usage:

<switches>
         <add name="MyTraceSwitch" value="4" />
   </switches>
 
For instance, if you set a TraceSwitch's Level property to TraceLevel.Info, then all the lower levels, from TraceLevel.Error to TraceLevel.Warning, will be included.
Above setting TraceSwitch value to 4 sets the trace level to Verbose,  As implied it turns on tracing level to verbose and also to all lower levels including Info, Warn and Error. 
 
TraceSwitch traceSwitch = new TraceSwitch("MyTraceSwitch", "Trace Switch");

Trace.WriteLineIf(traceSwitch.TraceError, "Testing Error Trace Switch.", traceSwitch.Description);
 
 
Trace Methods

The WriteLine and Write methods write output with and without a newline, respectively.
Trace.warn() is same as Trace.Write() only difference is that it produces output in red.
The WriteLineIf and WriteIf methods write output if a condition is true.
 
The Assert method displays a dialog and writes output when the specified condition evaluates to false.
The Fail method raises an assertion dialog and writes to output unconditionally. The benefit of the Fail method is that you can press the Retry button and break into the debugger to determine the cause of the problem.
You normally use the both the above methods with the Debug class. You don't normally want assertion message boxes popping up in front of users.
 
public ActionResult Index()
        {
            Trace.TraceWarning("This is a warning");
            Trace.Write("This is a message from Trace.Write", "category1");
           
            Trace.WriteLine("Message with a newline", "category2");
            Trace.WriteIf(true, "Trace.WriteIf()", "category1");

            Trace.WriteLineIf(true, "Trace.WriteLineIf()", "category2");
            Trace.Fail("Message from Trace.Fail");
            
            Trace.Flush();
            
            return View();
        } 
 
Note: The category parameter enables you to add category string, which is useful for filtering log entries.
 
Trace Listeners
 
DotNet have built in Trace Listeners defined, it is an collection of listeners which we can send output to example: VS IDE output widow, a file on your local disk, a Windows Event log, a SQL database, or a log file.
 
Well, there are two methods of defining trace listener first we have seen above using web.config next we are going to add in code.
 
DefaultTraceListener
It will redirect all trace output to the Visual Studio .Net Output window. The output is sent to a Win32 API called OutputDebugString.

TextWriterTraceListener
A TextWriterTraceListener writes trace output to a file or any output stream. Create an object and add to trace Listeners collection.
var fileName = Server.MapPath("~/TraceLog/WebTraceDemo.Log");
            TextWriterTraceListener newListener = new TextWriterTraceListener(fileName);
            Trace.Listeners.Add(newListener); 
 
EventLogTraceListener
Another trace listener that ships with .NET is the EventLogTraceListener, which writes to the Windows Event Log.
 
EventLogTraceListener eventLogListener = new EventLogTraceListener("MyEventLogTraceListener");
            Trace.Listeners.Add(eventLogListener);

related posts

Back to top