I have a TraceSource object that I use to log the initialization of a VB.Net application. It has several TraceListeners attached:
- ConsoleTraceListener
- TextWriterTraceListener
- EventLogTraceListener
For the first two I want the entry output to be "raw" - that is, without the standard header:
SourceName TraceEventType: Id :
I have implemented a wrapper that does this when the TraceEventType is set to Verbose:
If _buffer.EventType = TraceEventType.Verbose Then
For Each listener As TraceListener In _traceSource.Listeners
listener.Write(_buffer.Text)
Next
Else
_traceSource.TraceEvent(_buffer.EventType, id, _buffer.Text)
End If
I could do this for all the tracing, but then all entries in the EventLog would be listed with Level = Information. So I want to be able to specify the severity of the trace message, but I can't find any method on the TraceSource or the TraceListeners that allows me to do this. As far as I can tell, TraceListener has these options for writing to it:
- Write()
- WriteLine()
- TraceData()
- TraceEvent()
- TraceTransfer()
The last 3 allows for providing a TraceEventType (which correctly labels the EventLog entries, but the resulting output to the console and the log file then includes the prefixes and ends up like this (for example):
Bootstrapper Warning: 0 : Failed to validate assembly
Is there a way to override how the ConsoleTraceListener and TextWriterTraceListener format their output to not include this header, while at the same time being able to tag the entries with a TraceEventType (for the EventLog)?
This is the best I have come up with so far:
For Each listener As TraceListener In _traceSource.Listeners
If listener.GetType Is GetType(ConsoleTraceListener) OrElse listener.GetType Is GetType(TextWriterTraceListener) Then
listener.Write(_buffer.Text)
Else
listener.TraceEvent(Nothing, _traceSource.Name, _buffer.EventType, id, _buffer.Text)
End If
Next
This seems to work, but in the documentation on the TraceListener.TraceEvent Method from Microsoft, it says:
Important: This method is not intended to be called directly by application code but by members of the Debug, Trace, and TraceSource classes to write trace data to output.
..so I'm not sure if it's a good thing to do?
Edit:
I just realized that if I do something like my last example here, I don't need the TraceSource at all, since it's being bypassed anyway. But it also means I have to implement my own filtering and switching mechanisms (but that is maybe an OK price to pay to get it to work the way I want).