Does the .Net TraceSource/TraceListener framework have something similar to log4net's Formatters?

StackOverflow https://stackoverflow.com/questions/208735

  •  03-07-2019
  •  | 
  •  

Question

I've begun to the the built-in TraceSource and TraceListener classes and I would like to modify the output format of the events independently of the TraceSources and TraceListeners. It seems that the TraceListeners apply their own formatting. Is it possible to completely change the formatting without creating a new class for each and every TraceListener I use?

Was it helpful?

Solution

The Enterprise Library Logging Application Block (http://msdn.microsoft.com/en-us/library/cc309506.aspx) is built on the .Net TraceSource and TraceListener classes (so you can pretty much just drop it into your project and it'll work), and it supports a message formatter that you can configure in the web.config (or app.config).

OTHER TIPS

This is way late, but for any latecomers who might be looking for a TraceSource/TraceListener solution that supports formatting similar to that available in log4net, NLog, and LAB, you might try Ukadc.Diagnostics. You can configure the Ukadc-provided TraceListeners with a formatting string, and it will be applied when traces are written to the listener. You can also write your own tokens and add them to the formatting statement. For example, I wrote one for fun that simply increments a counter each time its value is retrieved. The result is that in the log file, each line receives a sequentially increasing number. I wrote another one that allows information from Trace.CorrelationManager.LogicalOperationStack to be added to the output.

I don't have easy access right now to my computer that has that work on it, or I would post these examples.

You can use the direct Write() or WriteLine() methods on Trace to put straight text into your TraceListener.

For anyone who ends up here and is still looking for custom formatting for TraceListeners, there is also Essential.Diagnostics https://essentialdiagnostics.codeplex.com/ (disclosure: I am involved in the project).

To answer the original question a TraceListener can accept custom properties in the configuration, so it is possible to write one TraceListener that handles multiple formats based on configuration, which might be more flexible than writing multiple.

This is what Essential.Diagnostics has, it has both a ColoredConsoleTraceListener and RollingFileTraceListener that support custom format strings, with many format values already available.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top