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.


Ben Foster

About Me

I'm a software engineer and aspiring entrepreneur with 12+ years experience in the tech industry and have worked with startups and SMB’s in areas such as healthcare, recruitment and e-commerce (I even worked in enterprise, once). I founded my first startup Fabrik in 2011.

I now head up the engineering team at Checkout.com. If you're interested in working in an exciting fin-tech company, drop me a message on Twitter.

Creative Commons Licence