How to enable tracing in ASP.NET Web API using Application Insights

If you were wondering on other day what this line from the default template does:

    config.EnableSystemDiagnosticsTracing();

Then know that it does exactly what is says: enables tracing using system.diagnostics API.

To forward this tracing to Application Insights, you need to install these two packages:

Install-Package Microsoft.AspNet.WebApi.Tracing
Install-Package Microsoft.ApplicationInsights.TraceListener

and add a trace listener:

<system.diagnostics>
  <trace autoflush="true">
    <listeners>
      <add name="AppInsightsListener" type="Microsoft.ApplicationInsights.TraceListener.ApplicationInsightsTraceListener, Microsoft.ApplicationInsights.TraceListener" />
    </listeners>
  </trace>
</system.diagnostic

That’s it! The Trace category is now being populated:

asp.net web api tracing ai

Happy tracing!