Pages

Jul 28, 2010

SharePoint Best Practices - Write to EventLog from SharePoint Custom Solutions

Just a quick thing to note, if you’re trying to write to the event log within your custom SharePoint solutions and run across this error:

Cannot open log for source {0}. You may not have write access.

This is definitely permissions related. A quick bit of searching and I found some useful info:

The CustomSD registry value for the Application event log is found under the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Applicationregistry key. It is a string value which uses Security Descriptor Definition Language (SDDL) to describe which accounts have access to which functions (e.g. read, write, clear) of the event log. By default the application event log will allow any IIS 6 application pool identity write access (either as a service logon or, in the case of custom accounts in the IIS_WPG group, as a batch logon). (reference: http://forums.asp.net/t/1131903.aspx)

So the key in the above paragraph is that the app pool identity already has permission to write to the event log, so instead of mucking around with permissions, I made sure my function for writing to the eventlog is elevated as follows:

public static void LogMessage(string message)
{
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        if (!EventLog.SourceExists("SharePoint Custom Solutions"))
        {
            EventLog.CreateEventSource("SharePoint Custom Solutions", "Application");
        }
        EventLog.WriteEntry("SharePoint Custom Solutions",
                                    message,
                                    EventLogEntryType.Error); 
});
}

No comments: