Tag Archives: SPGuidance

Using a Timer Job to ensure diagnostic areas of SPGuidance

In one of my previous posts, I described a PowerShell script that could be run on each front-end to ensure that for each diagnostic area defined in the logging framework, a corresponding event source was created. That script should be run with sufficient privileges on the target box, but does the job.

I then promised to post a method to do that from a timer job next, but work and private life has kept me busy lately 😉 My apologies. However, here it is.

In this post, I would like to expand on that a little, but instead of using the PowerShell route, I use a SharePoint Timer Job to accomplish the same thing.

You can download the example Visual Studio 2010 project from this location. What we will do in this post:

  1. Create a timer job that should be run on each front-end that ensures that for each diagnostic area, an event source is registered.
  2. Create two features:
    1. Diagnostics areas and categories
    2. Timer Job

In a real-world situation, I would publish the SPGuidance assemblies in a separate WSP, however, for simplicity; they are packaged with this solution.

I will create one diagnostic area called Boom.CustomLogging and two categories, called Connections and Events. From within the web part, I will log to both categories. In my next post, I will also show how to create a custom logging component. For this post, we use the default one (which logs to the event log and ULS logs).

First, open Visual Studio and create an empty SharePoint project. We will create three features:

  1. DiagnosticAreas à Sets up the diagnostic areas and categories
  2. JobInstaller à Will install our job to ensure the event sources
  3. WebParts à Will contain our test web part

Also create a Web Part element called LoggingTester and add it to the solution. Add Event receivers to the DiagnosticAreas and JobInstaller features. Finally, add a class to your project called EnsureEventSourcesJob.cs that will hold your timer job to ensure event sources. Your solution explorer should look something like this:

Configure Custom Diagnostic Areas

We will start with the event receiver for the Diagnostic areas. This feature receiver will set up our areas and categories that we will use in our sample. I want to configure one custom diagnostic area that is specific to my application and two categories beneath it.

  • Diagnostic Area: Boom.CustomLogging
    • Category: Connections (default event severity Error, default trace severity Medium)
    • Category: Events (default event severity Information, default trace severity Medium)

On the side, it is also possible to add categories to the default SharePoint 2010 diagnostic areas, such as Access Services, Excel Services Application and SharePoint Foundation Search, however, this is considered bad practice. In short, do not do it. Whenever you wish to introduce custom categories, do so in your own diagnostic area.

The following piece of code was taken from the SPGuidance chm. It defines a property in our event receiver class that returns a DiagnosticsAreaCollection with my custom areas and categories.

// This helper property builds a collection of areas and categories.
DiagnosticsAreaCollection _myAreas = null;
DiagnosticsAreaCollection MyAreas
   get {
      if (_myAreas == null)
         _myAreas = new DiagnosticsAreaCollection();
DiagnosticsArea boomArea = new DiagnosticsArea(“Boom.CustomLogging”);
         boomArea.DiagnosticsCategories.Add(new DiagnosticsCategory(“Events”, EventSeverity.Information, TraceSeverity.Medium));
         boomArea.DiagnosticsCategories.Add(new DiagnosticsCategory(“Connections”, EventSeverity.Error, TraceSeverity.Medium));


In this code snippet, we define a property that creates a new Microsoft.Practices.SharePoint.Common.Logging.DiagnosticsAreaCollection, creates a new Microsoft.Practices.SharePoint.Common.Logging.DiagnosticsArea called Boom.CustomLogging and finally adds two Microsoft.Practices.SharePoint.Common.Logging.DiagnosticsCategory objects that defines my two categories and adds it to the custom area. Finally, I add the area to the collection and return it.

No real magic here. We will use this property in both the feature activated and feature deactivating events. So, let us go in the feature activated event.

public override void FeatureActivated(SPFeatureReceiverProperties properties) {

configMgr = SharePointServiceLocator.GetCurrent().GetInstance<IConfigManager>();
   DiagnosticsAreaCollection configuredAreas = new DiagnosticsAreaCollection(configMgr);

(DiagnosticsArea newArea in MyAreas)
     var existingArea = configuredAreas[newArea.Name];
     if (existingArea == null) {
else {
        throw new SPException(“Diagnostic area already exists”);


In this method, we use the SharePointServiceLocator, which is also part of the Guidance framework, to return an instance of IConfigManager. The IConfigManager can be used to store configuration data on any level in SharePoint, so at Web, Site, WebApp and Farm level. Again, this is part of the Guidance framework and provides a single consistent framework to store configuration data that is not to be located in the web.config. Using the config manager, we request the current custom configured diagnostic areas. Then, for each area from our property (our new set), we check whether or not it already exists. If not, we add it. Finally, save the configuration again.

The feature deactivating method basically does the reverse, shown below.

public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {
   // Then remove the areas
   IConfigManager configMgr = SharePointServiceLocator.GetCurrent().GetInstance<IConfigManager>();
   DiagnosticsAreaCollection configuredAreas = new DiagnosticsAreaCollection(configMgr);
foreach (DiagnosticsArea area in MyAreas) {
      DiagnosticsArea areaToRemove = configuredAreas[area.Name];
      if (areaToRemove != null) {
         foreach (DiagnosticsCategory c in area.DiagnosticsCategories) {
            var existingCat = areaToRemove.DiagnosticsCategories[c.Name];
            if (existingCat != null) {
if (areaToRemove.DiagnosticsCategories.Count == 0) {


The only difference here is that we take a safe approach as suggested in the guidance, because other applications (depending on company guidelines) could have added categories to the diagnostic area. The safe way therefore is to remove the own configured categories and if none remain, remove the area.

Create the timer job to ensure event sources

In this section we will create a simple timer job that needs to be executed on every server in the farm. The job will call a method from the Guidance framework that will ensure that for each custom diagnostic area, a corresponding event source is created. This will have the same function as my PowerShell script in my previous post, just implemented through a timer job. The advantage here however, is that I can configure the timer job to run on specific intervals on all servers within the farm. The PowerShell script can also be scheduled and run remotely, but needs more management.

We define the timer job in the EnsureEventSourcesJob class.

public class EnsureSourcesJob : SPJobDefinition {
   public EnsureSourcesJob() : base() {}
EnsureSourcesJob(string name, SPWebApplication webApplication) : base(name, webApplication, null, SPJobLockType.None) {
      this.Title = name;

   public o
verride void Execute(Guid targetInstanceId)
      ILogger logger = SharePointServiceLocator.GetCurrent().GetInstance<ILogger>();
      logger.TraceToDeveloper(“Ensure Configured Diagnostic Areas registered timer job executing.”, 103, Microsoft.SharePoint.Administration.TraceSeverity.Monitorable, “Events”);
      // Important! The JobLockType should be set to None to run on each server!
      if (this.LockType == SPJobLockType.None) {
         // our job has only one very simple task.
         // call the ensure configured areas registered method of the DiagnosticsAreaEventSource class.

Two things are important in this job, which is quite simple. First, you need to provide a public parameter less constructor for the serialization. Second, the type of job specified should be of type SPJobLockType.None. This will ensure that my timer job will be run on each server within the farm.

The call to the DiagnosticsAreaEventSource.EnsureConfiguredAreasRegistered method will make sure that an event source for each of the configured diagnostic areas exists on the specific server.

Once the timer job has run, you can go to Central Admin à Diagnostic logging to see your own categories and events. They will be treated the same as any out of the box configured sources and categories.

The Visual Studio solution can be downloaded from here.