Aug 12, 2009

SharePoint Custom Application Logs in the EventViewer (source code)

Custom Logging to Event Viewer by SharePoint Custom code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace My.Foo.Bar
{
public class EventLogHandler
{
static string sSource = "My Portal";
static string sLog = "Application";                   //Change it to any specific name for categorization purpose in the Eventviewer.
//static string sEvent = "Error Occurred";

public static void AddApplicationEventLog(string exceptionDetails)
{
try
{
System.Security.Principal.WindowsImpersonationContext wic =
// make impersonation = false in the code.
System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero);

if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);

if (!string.IsNullOrEmpty(exceptionDetails))
{
//EventLog.WriteEntry(sSource, sEvent);
EventLog.WriteEntry(sSource, exceptionDetails,
EventLogEntryType.Error, 234);
}
else
EventLog.WriteEntry(sSource, "No Error Message", EventLogEntryType.Information, 234);

// again roll back the Impersonation = true
//ExceptionManager.Publish(e);
wic.Undo();
}
catch (Exception e1)
{
//do nothing
}
}
}
}

Usage from your custom code, once you have the above class as a part of your application:

EventLogHandler.AddApplicationEventLog("Your message for event viewer");
The Event Viewer doesn't display the custom log message, if the application is not registered for the logging in the event viewer. To register your custom application with the eventviewer,
Run the following console application:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace EventLogWriter
{
class Program
{
static void Main(string[] args)
{
try
{
string sSource = "My SP Web Portal";
string sLog = "Application";
string exceptionDetails = "Sample Entry";
try
{
System.Security.Principal.WindowsImpersonationContext wic =
// make impersonation = false in the code.
System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero);

if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);

if (!string.IsNullOrEmpty(exceptionDetails))
{
//EventLog.WriteEntry(sSource, sEvent);
EventLog.WriteEntry(sSource, exceptionDetails,
EventLogEntryType.Error, 234);
}
else
EventLog.WriteEntry(sSource, "No Error Message", EventLogEntryType.Information, 234);

// again roll back the Impersonation = true
//ExceptionManager.Publish(e);
wic.Undo();
}
catch (Exception e1)
{
//do nothing
}
}
catch (Exception ex)
{
}
}
}
}

No comments:

Pages