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

自古美人都是妖i 提交于 2019-12-06 02:05:34

问题


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?


回答1:


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).




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/208735/does-the-net-tracesource-tracelistener-framework-have-something-similar-to-log4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!