Web API: Introduction to SystemDiagnosticsTraceWriter

Today ASP.NET Team released 2012.2 update. One of the cool features is the support for .NET Native tracing capability.

The idea is all the trace information that is available while request flows through message handlers and formatters and find their way to the controller is now available now for you to consume.

For users starting on New Project with this update installed, this feature will be turned on automatically. See line config.EnableSystemDiagnosticsTracing in the snippet below


How does it work?

Let’s say you have a controller called “Values” and you do http://localhost/Webapi/api/Values. When you run it in visual studio, You get this by default in tracing window of VS. Here you find all the information that passed through various layers of WebAPI pipeline.


Now what if I want this output to be redirected to say console? It is extremely simple. Just throw this in your App.Config or Web.Config file.

Below, I’m adding ConsoleTraceListener for my Console App project. (You can add file or other tracelisteners if you like)


The output is as following and it is directed to console now.


That’s cool but what about internal stuff?

This whole magic is achieved when you do config.EnableSystemDiagnosticsTracing() via an extension method. Internally it looks like this.


SystemDiagnosticsTraceWriter is the class which makes this possible.

Here the extension method creates an instance of SystemDiagnosticsTraceWriter and then uses an extensibility feature of WebAPI to provide the implementation for ITraceWriter.

This implementation lives in an assembly called System.Web.Http.Tracing.dll which is also available as nuget package.

If you are working with earlier versions of WebAPI and cant upgrade, then just download the nuget package and then just provide implementation of ITraceWriter manually.