65.9K
CodeProject is changing. Read more.
Home

Logging to Event Viewer with DiagnosticsLevel - SharePoint 2007

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Dec 12, 2010

CPOL
viewsIcon

10781

Using the DiagnosticsLevel to decide on logging levels for custom webparts

The most least talked about is how to get the current DiagnosticsLevel of the "Areas" in SharePoint 2007. Unlike SharePoint 2010, finding the current DiagnosticsLevel in SharePoint 2007 is a bit tedious. If you want to decided on your web-part logging level(s) without registering a custom area, following is the easy way:
        public static void LogMessage(String errormsg, EventLogEntryType eventType, int eventID, short category)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPDiagnosticsService dsg = SPDiagnosticsService.Local;
                // Get the current levels.
                IEnumerable<IDiagnosticsLevel> levels = dsg.GetItems();
                // 
                foreach (IDiagnosticsLevel level in levels)
                {
                    if (level.Name == "WebParts")
                    {
                        switch (level.EventSeverity)
                        {
                            case EventSeverity.Error:               // Error : Information / Warning / Errors
                                break;
                            case EventSeverity.None:                // Do not log anything
                                return;
                            case EventSeverity.Warning:             // Warning : Information
                                if (eventType == EventLogEntryType.Error) return;
                                break;
                            case EventSeverity.Information:
                                if (eventType != EventLogEntryType.Information) return;
                                break;
                        }
                        break;
                    }
                }
                if (!EventLog.SourceExists("MyEventSource"))
                {
                    EventLog.CreateEventSource("MyEventSource", "MyAppLogs");
                }
                EventLog.WriteEntry("MyEventSource", errormsg, eventType, eventID, category);
            });
        }
This is a static method; so add it to your Web-Part and you can start logging. Enjoy coding.