"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Tracing in ASP.NET Web API 2

by Mike Wasson

When you are trying to debug a web-based application, there is no substitute for a good set of trace logs. This tutorial shows how to enable tracing in ASP.NET Web API. You can use this feature to trace what the Web API framework does before and after it invokes your controller. You can also use it to trace your own code.

Software versions used in the tutorial

Enable System.Diagnostics Tracing in Web API

First, we’ll create a new ASP.NET Web Application project. In Visual Studio, from the File menu, select New, then Project. Under Templates, Web, select ASP.NET Web Application.

Choose the Web API project template.

From the Tools menu, select Library Package Manager, then Package Manage Console.

In the Package Manager Console window, type the following commands.

[!code-consoleMain]

   1:  Install-Package Microsoft.AspNet.WebApi.Tracing
   2:  Update-Package Microsoft.AspNet.WebApi.WebHost

The first command installs the latest Web API tracing package. It also updates the core Web API packages. The second command updates the WebApi.WebHost package to the latest version.

[!NOTE] If you want to target a specific version of Web API, use the -Version flag when you install the tracing package.

Open the file WebApiConfig.cs in the App_Start folder. Add the following code to the Register method.

[!code-csharpMain]

   1:  public static class WebApiConfig
   2:  {
   3:      public static void Register(HttpConfiguration config)
   4:      {
   5:          // New code
   6:          config.EnableSystemDiagnosticsTracing();
   7:   
   8:          // Other configuration code not shown.
   9:      }
  10:  }

This code adds the SystemDiagnosticsTraceWriter class to the Web API pipeline. The SystemDiagnosticsTraceWriter class writes traces to System.Diagnostics.Trace.

To see the traces, run the application in the debugger. In the browser, navigate to /api/values.

The trace statements are written to the Output window in Visual Studio. (From the View menu, select Output).

Because SystemDiagnosticsTraceWriter writes traces to System.Diagnostics.Trace, you can register additional trace listeners; for example, to write traces to a log file. For more information about trace writers, see the Trace Listeners topic on MSDN.

Configuring SystemDiagnosticsTraceWriter

The following code shows how to configure the trace writer.

[!code-csharpMain]

   1:  SystemDiagnosticsTraceWriter traceWriter = config.EnableSystemDiagnosticsTracing();
   2:  traceWriter.IsVerbose = true;
   3:  traceWriter.MinimumLevel = TraceLevel.Debug;

There are two settings that you can control:

Adding Traces to Your Web API Application

Adding a trace writer gives you immediate access to the traces created by the Web API pipeline. You can also use the trace writer to trace your own code:

[!code-csharpMain]

   1:  using System.Web.Http.Tracing;
   2:   
   3:  public class ProductsController : ApiController
   4:  {
   5:      public HttpResponseMessage GetAllProducts()
   6:      {
   7:          Configuration.Services.GetTraceWriter().Info(
   8:              Request, "ProductsController", "Get the list of products.");
   9:   
  10:          // ...
  11:      }
  12:  }

To get the trace writer, call HttpConfiguration.Services.GetTraceWriter. From a controller, this method is accessible through the ApiController.Configuration property.

To write a trace, you can call the ITraceWriter.Trace method directly, but the ITraceWriterExtensions class defines some extension methods that are more friendly. For example, the Info method shown above creates a trace with trace level Info.

Web API Tracing Infrastructure

This section describes how to write a custom trace writer for Web API.

The Microsoft.AspNet.WebApi.Tracing package is built on top of a more general tracing infrastructure in Web API. Instead of using Microsoft.AspNet.WebApi.Tracing, you can also plug in some other tracing/loggin library, such as NLog or log4net.

To collect traces, implement the ITraceWriter interface. Here is a simple example:

[!code-csharpMain]

   1:  public class SimpleTracer : ITraceWriter
   2:  {
   3:      public void Trace(HttpRequestMessage request, string category, TraceLevel level, 
   4:          Action<TraceRecord> traceAction)
   5:      {
   6:          TraceRecord rec = new TraceRecord(request, category, level);
   7:          traceAction(rec);
   8:          WriteTrace(rec);
   9:      }
  10:   
  11:      protected void WriteTrace(TraceRecord rec)
  12:      {
  13:          var message = string.Format("{0};{1};{2}", 
  14:              rec.Operator, rec.Operation, rec.Message);
  15:          System.Diagnostics.Trace.WriteLine(message, rec.Category);
  16:      }
  17:  }

The ITraceWriter.Trace method creates a trace. The caller specifies a category and trace level. The category can be any user-defined string. Your implementation of Trace should do the following:

  1. Create a new TraceRecord. Initialize it with the request, category, and trace level, as shown. These values are provided by the caller.
  2. Invoke the traceAction delegate. Inside this delegate, the caller is expected to fill in the rest of the TraceRecord.
  3. Write the TraceRecord, using any logging technique that you like. The example shown here simply calls into System.Diagnostics.Trace.

Setting the Trace Writer

To enable tracing, you must configure Web API to use your ITraceWriter implementation. You do this through the HttpConfiguration object, as shown in the following code:

[!code-csharpMain]

   1:  public static void Register(HttpConfiguration config)
   2:  {
   3:      config.Services.Replace(typeof(ITraceWriter), new SimpleTracer());
   4:  }

Only one trace writer can be active. By default, Web API sets a “no-op” tracer that does nothing. (The “no-op” tracer exists so that tracing code does not have to check whether the trace writer is null before writing a trace.)

How Web API Tracing Works

Tracing in Web API uses a in Web API uses a facade pattern: When tracing is enabled, Web API wraps various parts of the request pipeline with classes that perform trace calls.

For example, when selecting a controller, the pipeline uses the IHttpControllerSelector interface. With tracing enabled, the pipleline inserts a class that implements IHttpControllerSelector but calls through to the real implementation:

Web API tracing uses the facade pattern.
Web API tracing uses the facade pattern.

The benefits of this design include:

You can also replace the entire Web API trace framework with your own custom framework, by replacing the default ITraceManager service:

[!code-csharpMain]

   1:  config.Services.Replace(typeof(ITraceManager), new MyTraceManager());

Implement ITraceManager.Initialize to initialize your tracing system. Be aware that this replaces the entire trace framework, including all of the tracing code that is built into Web API.



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/testing-and-debugging/tracing-in-aspnet-web-api.htm
< THANKS ME>