Enable/Disable asp.net health monitoring programatically

Nov 30, 2010 at 5:53 PM

Hello;

I know i can add a few settings to my web.config and have the it logging health monitoring events, which is a great feature.
But is there a way to enable/disable it via code?

Because we don't need (or want?) it enabled all the time, however, every time we do need it we will have to access to the web.config via ftp file or remote desktop and, the application will be restarted.
Using code we could just add an option to the settings page of the web application and be able to start/stop the health monitoring code by just clicking on a chekbox.

Coordinator
Nov 30, 2010 at 6:55 PM
Edited Dec 1, 2010 at 7:17 AM

This is not possible out of the box, but it is easy to create a provider that allows you to enable or disable logging at runtime and route the health monitoring system to that provider. Easiest would be to inherit from CompositeLoggingProvider. Below is a step-by-step to get what you need.

1. Create a new logging provider that inherits from the CompositeLoggingProvider and override the LogInternal method so you can suppress logging when needed:

public class RuntimeDisablingCompositeLoggingProvider
: CompositeLoggingProvider
{
// logging is enabled by default.
private static bool loggingEnabled = true;

public static bool LoggingEnabled
{
get { return this.loggingEnabled; }
set { this.loggingEnabled = value; }
}

protected override object LogInternal(LogEntry entry)
{
if (LoggingEnabled)
{
return base.LogInternal(entry);
}

return null;
}
}

 

2. Configure that logger in your configuration file and configure the logger to forward logging events to your actual logger:

<?xml version="1.0"?>
<configuration>
<configSections>
<section name="logging"
type="CuttingEdge.Logging.LoggingSection, CuttingEdge.Logging" />
</configSections>
<logging defaultProvider="WindowsEventLogger">
<providers>
<add
name="WindowsEventLogger"
type="CuttingEdge.Logging.WindowsEventLogLoggingProvider, CuttingEdge.Logging"
source="MyApplication"
logName="MyApplication"
/>
<add
name="DisablingLogger"
type="MyApp.RuntimeDisablingCompositeLoggingProvider, MyApp"
provider1="WindowsEventLogger"
/>
</providers>
</logging>
</configuration>

 

3. Change the configuration of the LoggingWebEventProvider to log to the DisablingLogger:

  <system.web>
<healthMonitoring heartbeatInterval="0" enabled="true">
<providers>
<add name="LoggingWebEventProvider"
type="CuttingEdge.Logging.Web.LoggingWebEventProvider, CuttingEdge.Logging"
loggingProvider="DisablingLogger" />
</providers>
<rules>
<add name="Custom Event Provider"
eventName="All Events"
provider="LoggingWebEventProvider"
profile="Default" />
</rules>
</healthMonitoring>
</system.web>

 

4. Write program code to enable or disable logging of events to the logger:

RuntimeDisablingCompositeLoggingProvider.LoggingEnabled = false;


Et voilà!  There you have it. I hope this helps.