In this article we will see how to enable/ use tracing for ASP.NET Web API. We will use the NuGet package Microsoft ASP.NET Web API Tracing.

#1. Open the Web API project(I will be using the project created in this article) in visual studio. Or we can open/ create any ASP.NET MVC 4 project with the Web API template.

#2. Lets install NuGet package Microsoft ASP.NET Web API Tracing, if not installed. Open package manager console and enter "Install-Package Microsoft.AspNet.WebApi.Tracing" and press Enter. For reference check below image:

Web API tracing blog sample Image 1

#3. Now lets enable it. Go to App_Start > WebApiConfig file > Register method. Add below line of code, if its not there:

config.EnableSystemDiagnosticsTracing();

#4. We are all set. Press F5 to run the project. Now open Output window and clear all data from there.

#5. Now open a web browser(i am using Firefox) and do a request to web API function. Like i used below URI:

http://sample.dev/api/teams/100

#6. Now open the Output window and check the trace lines. It gives a detailed information of steps for handling the HTTP GET request we did just now. For reference see below image:

Web API tracing blog sample Image 2

We can also create our custom trace writer. But our trace writer class should implement the ITraceWriter interface.

Let's implement it now!

#1. In above project, let's add a new class file as CustomWebApiTracer.cs and open the file. Make it implementing ITraceWriter. Include the namespace System.Web.Http.Tracing for this interface.

#2. Add below 2 functions in CustomWebApiTracer class.

public void Trace(HttpRequestMessage request,
                  string category,
                  TraceLevel level,
                  Action<TraceRecord> traceAction)
{
    if (level != TraceLevel.Off)
    {
        TraceRecord rec = new TraceRecord(request, category, level);
        traceAction(rec);
        WriteXmlElement(rec);
    }
}

private void WriteXmlElement(TraceRecord rec)
{
    using (Stream xmlFile = new FileStream(@"E:\Trace\trace.xml", FileMode.Append))
    {
        using (XmlTextWriter writer = new XmlTextWriter(xmlFile, Encoding.UTF8))
        {
            writer.Formatting = Formatting.Indented;
            writer.WriteStartElement("trace");
            writer.WriteElementString("timestamp", rec.Timestamp.ToString());
            writer.WriteElementString("operation", rec.Operation);
            writer.WriteElementString("user", rec.Operator);
            if (!String.IsNullOrWhiteSpace(rec.Message))
            {
                writer.WriteStartElement("message");
                writer.WriteCData(rec.Message);
                writer.WriteEndElement();
            }
            writer.WriteElementString("category", rec.Category);
            writer.WriteEndElement();
            writer.WriteString(Environment.NewLine);
            writer.Flush();
        }
    }
}

#3. Add the required namespaces used in above functions.

#4. To implement ItraceWriter, we will need to implement Trace method. In above Trace method what we did:

    - Created a new TraceRecord object. And invoked the caller’s traceAction, passing the TraceRecord object.

    - Called our helper WriteXmlElement function, which will write the output to a xml file.

    - In WriteXmlElement function, i used E:\Trace\trace.xml file, where all the tracing will be logged. You can adjust this file path as per your machine.

#5. Ok. But wait, we will need to let the application know, that it will use our custom trace writer. Let's open WebApiConfig file > Register method again and add below line:

config.Services.Replace(typeof(ITraceWriter), new WebApiTracer());

Make sure above line get added after config.EnableSystemDiagnosticsTracing();

We will need to add this namespace in that WebApiConfig file:

using System.Web.Http.Tracing;

#6. We are done. Now we can run the application and check the trace output generated in xml, at mentioned location.

Stay tuned, if looks interesting.

Reference:
Book: Practical ASP.NET Web API [Apress]

Previous > ASP.NET WEB API Part 3 - Web debugging with Fiddler and browser

Next > ASP.NET WEB API Part 5 - HTTP Response format (MediaTypeFormatter)

Discussion
5 X 6 =
** To prevent abusing comments from publishing, posted comments will be reviewed and then published!