Implement A Custom SharePoint 2010 Logging Service For ULS And Windows Event Log

Prior to Microsoft SharePoint 2010 there was no official documented way to programmatically use the built-in ULS service (Unified Logging Service) to log own custom messages. There are still solutions available on the internet that can be used, but SharePoint 2010 now supports full-blown logging service support.

To log a message to the SharePoint log files just call the WriteTrace method of the SPDiagnosticsService class:

1 SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("My Category", TraceSeverity.Medium, EventSeverity.Information), TraceSeverity.Medium, "My log message");

The problem with this technique is that the log entry does not contain any category information, instead SharePoint uses the value "Unknown":

image

Of course, that does not matter if someone develops small solutions. Developing custom solutions you may want to implement an own logging service with custom categories and UI integration within the Central Administration (CA) of SharePoint 2010.

This article shows how to develop a custom logging service that integrates with the Diagnostic Logging UI of the Central Administration:

image

Custom Logging Service

A custom logging service must inherit from the SPDiagnosticsServiceBase class. This is the base class for diagnostic services in SharePoint and it offers the option to log messages to log files via ULS and to the Windows Event Log. By overriding the ProvideAreas method the service provides information about diagnostic areas, categories and logging levels. A diagnostic area is a logical container of one or more categories.

The sample service defines one diagnostic area and one category (used by application pages) for this area:

1 [Guid("D64DEDE4-3D1D-42CC-AF40-DB09F0DFA309")]
2 public class LoggingService : SPDiagnosticsServiceBase
3 {
4 public static class Categories
5 {
6 public static string ApplicationPages = "Application Pages";
7 }
8
9 public static LoggingService Local
10 {
11 get { return SPFarm.Local.Services.GetValue(DefaultName); }
12 }
13
14 public static string DefaultName
15 {
16 get { return "Parago Logging Service"; }
17 }
18
19 public static string AreaName
20 {
21 get { return "Parago"; }
22 }
23
24 protected override IEnumerable ProvideAreas()
25 {
26 List areas = new List
27 {
28 new SPDiagnosticsArea(AreaName, 0, 0, false, new List
29 {
30 new SPDiagnosticsCategory(Categories.ApplicationPages, null, TraceSeverity.Medium,
31 EventSeverity.Information, 0, 0, false, true)
32 })
33 };
34
35 return areas;
36 }
37
38 // . . .
39
40 }

The area name as well as the category names will be also shown in the Diagnostic Logging UI of the CA. It is also possible to define a resource DLL to localize the names.

The service will offer the two static methods WriteTrace and WriteEvent. WriteTrace writes the log message to the SharePoint log files, usually saved in the SharePoint folder C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS.

The WriteEvent writes the log message to the Windows Event Log. The event source is called like the AreaName and later on created within the FeatureReceiver:

1 [Guid("D64DEDE4-3D1D-42CC-AF40-DB09F0DFA309")]
2 public class LoggingService : SPDiagnosticsServiceBase
3 {
4
5 ...
6
7 public static void WriteTrace(string categoryName, TraceSeverity traceSeverity,
8 string message)
9 {
10 if(string.IsNullOrEmpty(message))
11 return;
12
13 try
14 {
15 LoggingService service = Local;
16
17 if(service != null)
18 {
19 SPDiagnosticsCategory category = service.Areas[AreaName].Categories[categoryName];
20 service.WriteTrace(1, category, traceSeverity, message);
21 }
22 }
23 catch { }
24 }
25
26 public static void WriteEvent(string categoryName, EventSeverity eventSeverity,
27 string message)
28 {
29 if(string.IsNullOrEmpty(message))
30 return;
31
32 try
33 {
34 LoggingService service = Local;
35
36 if(service != null)
37 {
38 SPDiagnosticsCategory category = service.Areas[AreaName].Categories[categoryName];
39 service.WriteEvent(1, category, eventSeverity, message);
40 }
41 }
42 catch { }
43 }
44 }

The usage of the new custom logging service is quite simple:

1 // ULS Logging
2 LoggingService.WriteTrace(LoggingService.Categories.ApplicationPages,
3 TraceSeverity.Medium, "...");
4
5 // Windows Event Log
6 LoggingService.WriteEvent(LoggingService.Categories.ApplicationPages,
7 EventSeverity.Information, "...");

Next, we need to register it with SharePoint.

Service Registration

The custom logging service must be registered with SharePoint 2010 to show up in the Diagnostic Logging UI of the CA. The event sources also must be created on each server of the SharePoint farm. These two registration steps can be bundle within the FeatureActivated override method of the FeatureReceiver.

1 [Guid("50CA5F69-381F-4C2A-BE6C-F28219AFF20C")]
2 public class FeatureEventReceiver : SPFeatureReceiver
3 {
4 const string EventLogApplicationRegistryKeyPath =
5 @"SYSTEM\CurrentControlSet\services\eventlog\Application";
6
7 public override void FeatureActivated(SPFeatureReceiverProperties properties)
8 {
9 RegisterLoggingService(properties);
10 }
11
12 public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
13 {
14 UnRegisterLoggingService(properties);
15 }
16
17 static void RegisterLoggingService(SPFeatureReceiverProperties properties)
18 {
19 SPFarm farm = properties.Definition.Farm;
20
21 if(farm != null)
22 {
23 LoggingService service = LoggingService.Local;
24
25 if(service == null)
26 {
27 service = new LoggingService();
28 service.Update();
29
30 if(service.Status != SPObjectStatus.Online)
31 service.Provision();
32 }
33
34 foreach(SPServer server in farm.Servers)
35 {
36 RegistryKey baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine,
37 server.Address);
38
39 if(baseKey != null)
40 {
41 RegistryKey eventLogKey = baseKey.OpenSubKey(EventLogApplicationRegistryKeyPath,
42 true);
43
44 if(eventLogKey != null)
45 {
46 RegistryKey loggingServiceKey = eventLogKey.OpenSubKey(LoggingService.AreaName);
47
48 if(loggingServiceKey == null)
49 {
50 loggingServiceKey = eventLogKey.CreateSubKey(LoggingService.AreaName,
51 RegistryKeyPermissionCheck.ReadWriteSubTree);
52 loggingServiceKey.SetValue("EventMessageFile",
53 @"C:\Windows\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll",
54 RegistryValueKind.String);
55 }
56 }
57 }
58 }
59 }
60 }
61
62 static void UnRegisterLoggingService(SPFeatureReceiverProperties properties)
63 {
64 SPFarm farm = properties.Definition.Farm;
65
66 if(farm != null)
67 {
68 LoggingService service = LoggingService.Local;
69
70 if(service != null)
71 service.Delete();
72
73 foreach(SPServer server in farm.Servers)
74 {
75 RegistryKey baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine,
76 server.Address);
77
78 if(baseKey != null)
79 {
80 RegistryKey eventLogKey = baseKey.OpenSubKey(EventLogApplicationRegistryKeyPath,
81 true);
82
83 if(eventLogKey != null)
84 {
85 RegistryKey loggingServiceKey = eventLogKey.OpenSubKey(LoggingService.AreaName);
86
87 if(loggingServiceKey != null)
88 eventLogKey.DeleteSubKey(LoggingService.AreaName);
89 }
90 }
91 }
92 }
93 }
94 }

The FeatureActivated override is calling the RegisterLoggingService helper method to register with the SharePoint system if the service is not already available. Since one of the base classes of LoggingService is the SPService class which provides an Update and Provision method, we can register the new service farm-wide.

The second step is to create a new Windows Event Log source. Therefore we have to go through the collection of SharePoint farm servers and remotely add the new source by generating registry entries on each server.

To unregister we redo the registration steps by overriding FeatureDeactivating method of the FeatureReceiver class. The UnRegisterLoggingService method then deletes the service and removes all registry keys on all servers in the SharePoint farm.

The sample solution also created an application page to test the logging service. The source code is available as download.

image

Enter a test message and press the Log button. The message will be logged to the Windows Event Log:

And to the SharePoint log files:

image

That's it.

Download Source Code | Download PDF Version