Search code examples
azure-web-app-servicesystem.diagnostics

Azure API Apps Diagnostics


I have an Azure API App that needs to log trace data, so have chosen to use Azure Diagnostics and .Net System.Diagnostics.Trace.

The trace message logs to Table Storage, but the Event Id field is 0. The documentation online suggests 0 is the default value, but I cannot see an obvious way to set the Event Id.

Trace.TraceError, Trace.TraceInformation and Trace.TraceWarning only take a string or a formatted message.

Would some know if it is possible to set the Event Id and if so how?

Thanks Andy


Solution

  • Although I cannot take credit for the answer, I thought I should post the answer I found here: https://blogs.msdn.microsoft.com/mcsuksoldev/2014/09/04/adding-trace-to-azure-web-sites-and-web-jobs/

    Basically you use the System.Diagnostics.TraceSource type and call the TraceEvent() method. Although this won't work without some configuration first.

    There are three trace listeners to be aware of, although for just TableStorage it is only the first:

    • AzureTableTraceListener
    • AzureBlobTraceListener
    • AzureDriveTraceListener

    You will need to install the nuget package: Microsoft.WindowsAzure.WebSites.Diagnostics

    The code example from the link above is:

    public static readonly TraceSource Operational = new TraceSource("Operational");
    Operational.TraceEvent(TraceEventType.Verbose, 101, "TraceEvent WebSite Operational");
    

    For the TraceSource to log to TableStorage you need to add the following to the web.config:

    <system.diagnostics>
    <sharedListeners>
      <add name="AzureTableTraceListener" type="Microsoft.WindowsAzure.WebSites.Diagnostics.AzureTableTraceListener, Microsoft.WindowsAzure.WebSites.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </sharedListeners>
    <sources>
      <source name="Operational" switchName="OperationalSourceSwitch" switchType="System.Diagnostics.SourceSwitch">
        <listeners>
          <add name="AzureTableTraceListener"/>
          <add name="AzureBlobTraceListener"/>
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="OperationalSourceSwitch" value="All" />
    </switches>
    <trace autoflush="true" indentsize="4" />
    

    Andy