Time-Tagged Trace Listener
—
How to time-tag the entries in the output window
Problem
You have a lot of trace/debug output in the debug window,
you want an indication of when the entries were written.
Solution
Create a custom TraceListener that puts a date/time tag on each line written.
Discussion
Inherit from DefaultTraceListener, as DefaultTraceListener writes to the debug output window.
Override the TraceListener.WriteIndent sub as this is the sub that starts a new line of output
| Member | Description |
|---|
| m_formatInfo | An IFormatProvider that supplies culture-specific formatting information
NOTE: If a null reference (Nothing) the CultureInfo.CurrentCulture DateTimeFormatInfo will be used |
|---|
| m_formatString | A format string
NOTE: If a null reference (Nothing) the ‘G’ format is used |
|---|
| FormatInfo | An IFormatProvider that supplies culture-specific formatting information |
|---|
| FormatString | A format string |
|---|
| WriteIndent | Overridden to prefix each line with DateTime.Now formatted according to the FormatInfo & FormatString |
|---|
NOTE: A desired enhancement would be to read the formatting information from the configuration/system.diagnostics/trace/listeners element of the app.config.
Example
Sample code replacing the standard TraceListeners with a TimeTaggedDefaultTraceListeners
NOTE: Sets the formatting to ‘g’ for short date & short time.
Debug.Listeners.Clear()
Dim listener As New TimeTaggedDefaultTraceListener
listener.FormatInfo = Nothing
listener.FormatString = "g"
Debug.Listeners.Add(listener)
Source
Define the TimeTaggedDefaultTraceListener type.
Option Strict On
Option Explicit On
Public Class TimeTaggedDefaultTraceListener
Inherits System.Diagnostics.DefaultTraceListener
Private m_formatInfo As IFormatProvider
Private m_formatString As String
Public Property FormatInfo() As IFormatProvider
Get
Return m_formatInfo
End Get
Set(ByVal value As IFormatProvider)
m_formatInfo = value
End Set
End Property
Public Property FormatString() As String
Get
Return m_formatString
End Get
Set(ByVal value As String)
m_formatString = value
End Set
End Property
Protected Overrides Sub WriteIndent()
MyBase.NeedIndent = False
MyBase.Write(DateTime.Now.ToString(m_formatString, m_formatInfo))
MyBase.Write(": ")
MyBase.NeedIndent = True
MyBase.WriteIndent()
End Sub
End Class
Alternate WriteIndent method for TimeTaggedDefaultTraceListener that indents the tags
Protected Overrides Sub WriteIndent()
MyBase.WriteIndent()
MyBase.Write(DateTime.Now())
MyBase.Write(": ")
End Sub
See Also