VB .NET: Advanced logging method

24. Aug 2008 20:39 (bearbeiten)


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"
  1. Public Shared Sub AddToLog(ByVal aMessage As String)
  2.  
  3. If Not My.Settings.Logging Then Exit Sub
  4.  
  5. Dim nle As String ' new list entry
  6. Dim acn As String ' A caller name
  7.  
  8. ' if logging of stack is enabled put together some info
  9. ' 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
  10. If My.Settings.LogStack Then
  11.  
  12. Dim sf As System.Diagnostics.StackFrame
  13. ' the calling method is always frame 1 of the call stack (the current method is frame 0)
  14. sf = New System.Diagnostics.StackTrace().GetFrame(1)
  15. acn = sf.GetMethod.ReflectedType.Name & "." & sf.GetMethod.Name
  16.  
  17. Else
  18. acn = ""
  19. End If
  20.  
  21. ' setup log string
  22. nle = Now.ToShortDateString & " : " & Now.ToShortTimeString & " : " & acn & " : " & aMessage
  23.  
  24. ' Add to log
  25. ' note: you could also add the nle string to a listbox or something else...
  26. My.Application.Log.DefaultFileLogWriter.WriteLine(nle)
  27. My.Application.Log.DefaultFileLogWriter.Flush()
  28. End Sub

Tags ¦ , und