May 12, 2016

How to use TraceSource with Azure Diagnostics

Recently I was trying to diagnose a production issue involving OWIN Authentication middleware and found that trace output was not being written to Azure logs.

The middleware used Microsoft’s OWIN Logging framework which uses TraceSource internally.

The first step was to enable the Microsoft.Owin trace switch, which can be done in web.config:

<configuration>
  <system.diagnostics>
    <switches>
      <add name="Microsoft.Owin" value="Verbose" />
    </switches>
  </system.diagnostics>
</configuration>

This is enough to write OWIN trace output to Visual Studio’s output window but to get it working in Azure we also have to set up the appropriate trace listeners:

<configuration>
  <system.diagnostics>
    <sharedListeners>
      <add name="AzureDriveTraceListener" type="Microsoft.WindowsAzure.WebSites.Diagnostics.AzureDriveTraceListener, Microsoft.WindowsAzure.WebSites.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </sharedListeners>
    <sources>
      <source name="Microsoft.Owin" switchName="Microsoft.Owin" switchType="System.Diagnostics.SourceSwitch">
        <listeners>
          <add name="AzureDriveTraceListener"/>
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="Microsoft.Owin" value="Verbose" />
    </switches>
  </system.diagnostics>
</configuration>

Here I’m using the AzureDriveTraceListener which is enough for file system application logging (and streaming logs). If you want to write to Azure Blob or Table storage you can use the following listeners:

<add name="AzureTableTraceListener" type="Microsoft.WindowsAzure.WebSites.Diagnostics.AzureTableTraceListener, Microsoft.WindowsAzure.WebSites.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="AzureBlobTraceListener" type="Microsoft.WindowsAzure.WebSites.Diagnostics.AzureBlobTraceListener, Microsoft.WindowsAzure.WebSites.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

I recommend making the above changes using a web.config transformation otherwise you’ll be sending output to Azure during development.

© 2020 Ben Foster