codingoutloud
11/17/2012 - 8:33 PM

Enable Diagnostic Trace Logging for Windows Azure Compute Emulator from ASP.NET

Enable Diagnostic Trace Logging for Windows Azure Compute Emulator from ASP.NET

// Code snippet for use in Windows Azure Cloud Services. 
// The EnableDiagnosticTraceLoggingForComputeEmulator method can be called from ASP.NET
// code to enable output from the System.Diagnostics.Trace class to appear in the
// Windows Azure Compute Emulator. The method does nothing when deployed to the cloud,
// when run outside the compute emulator, when run other than in DEBUG, or run repeatedly.
//
// The code uses Reflection to dynamically load the needed assembly and create the
// specific TraceListener class needed.
//
// EXAMPLE INITIALIZING FROM Global.asax.
// protected void Application_Start()
// {
//    // .. other config
//    EnableDiagnosticTraceLoggingForComputeEmulator();
// }
//
// EXAMPLE BENEFIT - ASP.NET MVC Controller
// public ActionResult Index()
// {
//    Trace.TraceInformation("This message ONLY show up in the Windows Azure Compute Emulator" +
//                           " if EnableDiagnosticTraceLoggingForComputeEmulator() has been called!");
//    return View();
// }
//
// Bill Wilder | @codingoutloud | Nov 2012
// Original: https://gist.github.com/4099954

using System.Reflection;
using System.Diagnostics;

[Conditional("DEBUG")] // doc on the Conditional attribute: http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx
void EnableDiagnosticTraceLoggingForComputeEmulator()
{
   try
   {
      if (RoleEnvironment.IsAvailable && RoleEnvironment.IsEmulated)
      {
         const string className = 
            "Microsoft.ServiceHosting.Tools.DevelopmentFabric.Runtime.DevelopmentFabricTraceListener";

         if (Trace.Listeners.Cast<TraceListener>().Any(tl => tl.GetType().FullName == className))
         {
            Trace.TraceWarning("Skipping attempt to add second instance of {0}.", className);
            return;
         }

         const string assemblyName =
            "Microsoft.ServiceHosting.Tools.DevelopmentFabric.Runtime, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
         //var path = Assembly.ReflectionOnlyLoad(assemblyName).Location;
         //Assembly assembly = Assembly.LoadFile(path);
         var assembly = Assembly.LoadFile(assemblyName);
         var computeEmulatorTraceListenerType = assembly.GetType(className);
         var computeEmulatorTraceListener = (TraceListener)Activator.CreateInstance(computeEmulatorTraceListenerType);
         System.Diagnostics.Trace.Listeners.Add(computeEmulatorTraceListener);
         Trace.TraceInformation("Diagnostic Trace statements will now appear in Compute Emulator: {0} added.", className);
      }
   }
   catch (Exception)
   {
      // eat any exceptions since this method offers a No-throw Guarantee 
      // http://en.wikipedia.org/wiki/Exception_guarantees
   }
}