Use of Tracing in Web API2

Introduction

This article explains how to do tracing in Web API 2. Tracing is used for finding the ITracewriter instance. If the ITraceWriter instance is present then we use tracing otherwise tracing is not used.

Features of Tracing:

  • Application Level Tracing

This type of tracing allows you to see the recent tracing data without restarting the tracing session. It removes the older tracing data and only displays the recent data.

  • Integrating tracing functionality

The class "System.Diagnostics.Trace" is for the tracing output and we can forward the instrumentation events to this class.

  • Programmatic to trace message

It allows you to access and manipulate the trace.

Now see the use of tracing in the Web API.

Step 1

First we create a Web API Project as in the following:

  • Start Visual Studio 2013.
  • From the Start Window select "New Project".
  • Select "Installed" -> "Template" -> "Visual C#" -> "Web" and select the "ASP.NET web Application".

create web application.jpg

  • Click on the "OK" button.

Select Web API

  • From the Project window select the "Web API" template.

Step 2

Now install the "Microsoft ASP.NET Web API2 Tracing" form the NuGet package manager.

  • Go To tools menu Select "Library Package Manager".
  • The select "Manage Nuget Packages for Solutions".
  • And install the "Microsoft ASP.NET Web API2 Tracing".

Install Tracing package

Step 3

There are two ways to enable the default TraceWirter, the first is a short route and another is a long route. For the short route add the simple code to the "Global.asax.cs" that is "confog.EnableSystemDiagnosticsTracing()." And in the other, the long route, we can add the class in the App_Start folder named "TracingConfig.cs". So we add a class in this folder:

  • Right-click on the App_Start folder then select "Add" -> "Class".
  • Change the name and click on the "Ok" button.

Add TraceConfic class

Step 4

Now we add a static method in the "TraceConfig.cs" file that is the Register method.

public static void Register(HttpConfiguration config)

        {

        }

Step 5

In this step we will ensure that the config is not null; if it is null then it throws an exception. We also create the SystemDiagnosticsTraceWriter instance.

The entire code looks like this:

public class TracingConfig

    {

        public static void Register(HttpConfiguration config)

        {

            if (config == null)

            {

                throw new ArgumentNullException("config",

                    @"Expected type HttpConfiguration.");

            }

            SystemDiagnosticsTraceWriter writer = new SystemDiagnosticsTraceWriter()

            {

                MinimumLevel = TraceLevel.Info,

                IsVerbose = false

            };

        }

    }

Step 6

Now the Register method will call where the other configurations are called from the application_start in the global.asax.

protected void Application_Start()

        {

            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

            TracingConfig.Register(GlobalConfiguration.Configuration);

        }

Step 7

Now we run the application and the actual URL navigate with the "http://localhost:6564/api/values" and we can see the bunch of information:

execute application

Output of tracing

Step 8

Now we write the trace logs code from the custom code.

Using the preceding we can see how the ITraceWriter has started the Writing Tracing information. We will also wrap the Tracing method with the WriteToTrace  method. For categorizing your trace it takes a string. In the ValuesController add the following code:

 private void WriteToTrace(string category, string log, System.Web.Http.Tracing.TraceLevel level)

        {

            ITraceWriter trceriter = Configuration.Services.GetTraceWriter();

            if (trceriter != null)

            {

                trceriter.Trace(

                    Request, category, level,

                    (traceRecord) =>

                    {

                        traceRecord.Message =

                            String.Format("In this custom code = {0}", log);

                    });

            }

        }

Now we will invoke our WriteToTrace method from the Get method that specifies the Trace as a part of the category that is called the Controller.

// GET api/values

        public IEnumerable<string> Get()

        {

            WriteToTrace("Controllers""There are 2 elements in the return array"TraceLevel.Info);

            return new string[] { "value1""value2" };

 

        }

Now we will again execute the application and navigate to the URL, we will see the additional information in the trace output.

traceinformation

Up Next
    Ebook Download
    View all
    Learn
    View all