Public MustInherit Class ExceptionLogger Protected mstrEventSource As String Public Sub WriteToEventLog(ByVal strMessage As String, ByVal enmType As EventLogEntryType) Try If (Not EventLog.SourceExists(mstrEventSource)) Then EventLog.CreateEventSource(mstrEventSource, "Application") End If EventLog.WriteEntry(mstrEventSource, strMessage, enmType) Catch ex As Exception End Try End Sub Public Sub LogException(ByVal objException As Exception, Optional ByVal strClassName As String = "", Optional ByVal strMethodName As String = "") Dim objStackFrame As StackFrame = New System.Diagnostics.StackFrame(1) Dim intLineNumber As Integer = objStackFrame.GetFileLineNumber() Dim strFile As String = objStackFrame.GetFileName ' If no class/method information was passed in, get the information from the call stack If (strClassName = "" And strMethodName = "") Then Dim objMethod As System.Reflection.MethodBase = objStackFrame.GetMethod() strClassName = objMethod.ReflectedType.FullName strMethodName = objMethod.Name End If Dim strMessage As String = "Exception Details:" & ControlChars.CrLf If (strClassName <> "") Then strMessage = strMessage & "Class:" & ControlChars.Tab & strClassName & ControlChars.CrLf End If If (strMethodName <> "") Then strMessage = strMessage & "Method:" & ControlChars.Tab & strMethodName & ControlChars.CrLf End If If (intLineNumber <> 0) Then strMessage = strMessage & "Line:" & ControlChars.Tab & intLineNumber & ControlChars.CrLf End If If (strFile <> "") Then strMessage = strMessage & "File:" & ControlChars.Tab & strFile & ControlChars.CrLf End If strMessage = strMessage & "Details:" & ControlChars.Tab & objException.Message & ControlChars.CrLf ' Walk through all innerExceptions, adding their message to the combined message If (Not objException.InnerException Is Nothing) Then strMessage = strMessage & ControlChars.CrLf & "Inner exceptions:" & ControlChars.CrLf Dim objExceptionWalker As Exception = objException While (Not objExceptionWalker.InnerException Is Nothing) objExceptionWalker = objExceptionWalker.InnerException strMessage = strMessage & ControlChars.CrLf & "Message:" & ControlChars.CrLf strMessage = strMessage & objExceptionWalker.Message & ControlChars.CrLf End While End If WriteToEventLog(strMessage, EventLogEntryType.Error) End Sub Public Sub New() mstrEventSource = My.Application.Info.Title End Sub Public Sub New(ByVal strEventSource As String) mstrEventSource = strEventSource End Sub End Class
Exception Logging to the Event Log
Category: Uncategorized |
Leave a Reply
You must be logged in to post a comment.