5

I'm trying to create a custom webpart. To implement error handling I would like to write to the eventlog. To do so, I'm trying to use the following code;

protected void btnExceptionTester_Click(object sender, EventArgs e)
    {
        try
        {
            throw new Exception("this is a test");
        }
        catch (Exception ex)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                EventLog.WriteEntry("TestWebpart", ex.ToString(), EventLogEntryType.Error);
            });
        }
    }

When I try to execute this code, I receive an sharepoint error page (unhandled exception). When I look in the eventlog, I see the following message; "Requested registry access is not allowed".

I'm runnning (for testing only) under the full trust level. Can someone point out to me what kind of privileges I would need to write to the eventlog? Or is there another approach?

Help greatly appriciated!

Obelix
  • 708
  • 11
  • 24

3 Answers3

8

I haven't tried writing to the Windows event log but as an alternative you can write to the SharePoint logs in the 12 hive using the following:

Microsoft.Office.Server.Diagnostics.PortalLog.LogString("your message here!");

Hope this helps

Iain

Temple
  • 1,079
  • 1
  • 10
  • 22
  • 1
    Is there a special reference needed in order to use this one? I'm running under MOSS2007 and added the MS Sharepoint reference but i'm not able to get to that office/portal namespace. – Obelix May 12 '09 at 11:16
  • 1
    ah yes, you need to add a reference to Microsoft.Office.Server – Temple May 12 '09 at 11:48
  • That did the trick. My logs are now shown in the 12 hive log files. – Obelix May 13 '09 at 08:11
  • This class is marked with "This class and its members are reserved for internal use and are not intended to be used in your code.". – skolima Aug 18 '10 at 07:46
  • To log to ULS, use SPDiagnosticsService.Local : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spdiagnosticsservice.local.aspx – skolima Aug 18 '10 at 08:28
  • You can also use Microsoft.Office.Server.Diagnostics.PortalLog.DebugLogString() if you want to specify the error level for the log entry. – Anthony Graglia Oct 05 '12 at 14:38
1

Update

Writing to the event log requires elevated privileges in the web part:

SPSecurity.RunWithElevatedPrivileges(delegate { EventLog.WriteEntry(...

The permissions on:

HKLM\SYSTEM\CurrentControlSet\Services\Eventlog\YourWebPartLog

I think are the cause of your grief. What are the permissions on that vs. the permissions of your application pool?

vinny
  • 1,810
  • 15
  • 21
1

EventLog Entries in SharePoint:

  1. For WebParts Log the errors in the ULS logs which is present in 12 hive.

  2. For SharePoint Application pages, wrtie the errors in the Event Logs.

  3. All other list and Library related errors will be noted down in the ULS logs only.

Thanks

shakir
  • 11
  • 1