Search
Website

ASP.NET 4 in VB 2010 : Logging Exceptions (part 2) - Writing to the Event Log

Published 2 min readBy Programming4us Editorial Team

2. Writing to the Event Log

You can interact with event logs in an ASP.NET page by using the classes in the System.Diagnostics namespace. First, import the namespace at the beginning of your code-behind file:

Imports System.Diagnostics

The following example rewrites the simple ErrorTest page to use event logging:

Public Partial Class ErrorTestLog
Inherits System.Web.UI.Page

Protected Sub cmdCompute_Click(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles cmdCompute.Click


Try
Dim A, B, Result As Decimal
A = Decimal.Parse(txtA.Text)
B = Decimal.Parse(txtB.Text)
Result = A / B
lblResult.Text = Result.ToString()
lblResult.ForeColor = System.Drawing.Color.Black
Catch err As Exception
lblResult.Text = "<b>Message:</b> " & err.Message & "<br /><br />"
lblResult.Text &= "<b>Source:</b> " & err.Source & "<br /><br />"
lblResult.Text &= "<b>Stack Trace:</b> " & err.StackTrace
lblResult.ForeColor = System.Drawing.Color.Red

' Write the information to the event log.
Dim Log As New EventLog()
Log.Source = "DivisionPage"
Log.WriteEntry(err.Message, EventLogEntryType.Error)
End Try
End Sub

End Class


The event log record will now appear in the Event Viewer utility, as shown in Figure 4. Note that logging is intended for the system administrator or developer. It doesn't replace the code you use to notify the user and explain that a problem has occurred.

Figure 4. An event record