Monday, November 12, 2007

Writing to the Event Log

In ASP.NET, error can be handled programmatically by writing appropriate code in the page-level error event, for errors on an individual page or in the application-level error event for handling errors that may occur in any page of the application.

Therefore, code for writing in the Event Log should be written in either of the events, depending on the requirement of the application. To illustrate this example, I have written the code in the application-level event with the error mode set to "RemoteOnly" and the defaultRedirect attribute to error.htm. The application-level error event should be included in the global file global.asax within the same application folder.

The contents of the global file can be given as follows:

Writing Log Entry in the Event Log

Imports System.Web
Imports System.Web.SessionState
Imports System.Diagnostics

Public Class Global
Inherits System.Web.HttpApplication

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

Dim ErrorDescription As String = Server.GetLastError.ToString

'Creation of event log if it does not exist
Dim EventLogName As String = "ErrorSample"
If (Not EventLog.SourceExists(EventLogName)) Then
EventLog.CreateEventSource(EventLogName, EventLogName)
End If

' Inserting into event log
Dim Log As New EventLog()
Log.Source = EventLogName
Log.WriteEntry(ErrorDescription, EventLogEntryType.Error)

End Sub

End Class

No comments: