VB .NET: Advanced logging method

The following function adds aMessage to the applications DefaultLogWriter. The DefaultLogWriter is a nice little feature included in Visual Basic .NET which allows you to automatically create a log file in the "Documents and Settings" folder of your application to which you can add your log entries via WriteLine(aMessage).

The function below also adds some more information to the log entry itself. It adds the current date and time and also retrieves the calling method from stack, which can be useful for tracking down a bug (thanks go out to skybound.ca for his help here).

The output could look like this:

"23.08.2008 16:15:43 : CreateListViewItem : Added new item"

Public Shared Sub AddToLog(ByVal aMessage As String)
 
    If Not My.Settings.Logging Then Exit Sub
 
    Dim nle As String ' new list entry
    Dim acn As String ' A caller name

    ' if logging of stack is enabled put together some info
    ' note: i put this as an option to the application.settings because when adding many entries to the log you might want to speed up things a bit by disabling logging the stack info
    If My.Settings.LogStack Then
 
      Dim sf As System.Diagnostics.StackFrame
      ' the calling method is always frame 1 of the call stack (the current method is frame 0)
      sf = New System.Diagnostics.StackTrace().GetFrame(1)
      acn = sf.GetMethod.ReflectedType.Name & "." & sf.GetMethod.Name
 
    Else
      acn = ""
    End If
 
    ' setup log string
    nle = Now.ToShortDateString & " : " & Now.ToShortTimeString & " : " & acn & " : " & aMessage
 
    ' Add to log
    ' note: you could also add the nle string to a listbox or something else...
    My.Application.Log.DefaultFileLogWriter.WriteLine(nle)
    My.Application.Log.DefaultFileLogWriter.Flush()
  End Sub

0 Antworten zu VB .NET: Advanced logging method

  1. Bisher gibt es keine Kommentare.