Configuration, System.Diagnostics and Medium Trust

In the past, I have widely used, and been a fan of, TextWriterTraceListener and EventLogTraceListener configured via the web.config in order to output diagnostics information from a web app or site.  These things have been there since .Net 1, so our main library of code has hooks into System.Diagnostics.  We even implemented a messaging aspect to this so that certain critical errors would trigger an SMTP message to us.  This has been invaluable in determining what is happening with a site as content changes, or something happens that we need to take action on before a complaint comes in.  (Who am I kidding – this is how we find out about bugs that got missed for whatever reason).

A few months ago, a site we had hosted on a 3rd party provider decided they would switch the site to Medium trust, so all of that diagnostics code was busted.   The diagnostics config was done using a custom configuration section, so that didn’t work, neither did any method that referenced any class from System.Diagnostics.

To make matters worse, our error emails weren’t sending out either, since the smtp server was working using a drop folder that was outside out our app folder… gah.  It wasn’t good.

 

So how did we get around this problem?

The configuration section was easy to fix – you just need to read the web.config as an XmlDocument and populate your configuration object manually.  I also recommend caching this in Application (remember to use lock() when accessing this collection..) so that the Xml parsing only has to happen once per application life cycle.

The Diagnostics stuff is a complete wash – you need to switch out all of this code (luckily ours was all routing through a single method, so it wasn’t too crazy) and replace it was custom logic to write to files, event logs, whatever.  I went with the quick and dirty approach and used the System.IO.File.AppendAllText() method.  This may not be as efficient as keeping the file handle open throughout the application, but it also means that you don’t have to worry about having an open file-handle either…  of course the AppendAllText call is wrapped in a lock() so that only one thread can write to the log at once.  The general idea is that your app shouldn’t be spitting out copious amounts of logging unless you are in a problem situation anyways…

As for the SMTP issue – the provider gave us credentials to send messages through a normal SMTP relay, so that ended up being fine.

 

The moral of this story?  Think twice before using System.Diagnostics on a site that will be hosted on a third part provider…

 

(Special Note: apparently Azure will be NOT be limited to medium trust… sweet!)

 

more later - joel

No Comments