How to use custom trace listener to log traces in .net

I have come across this link http://www.codeproject.com/Articles/447238/Advanced-Tracing#_comments. And the author did quite a nice job of creating a Custom listener that logs to a DataBase. While researching more on tracing/logging I read (from here https://blogs.msdn.microsoft.com/bclteam/2005/09/20/a-tracing-primer-part-ii-b-mike-rousos/) that the trace source calls the following methods when it needs to trace through a listener.

    void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id)
    void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string message)
    void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string format, params object[] args)
    void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, object data)
    void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data)
    void TraceTransfer(TraceEventCache eventCache, String source, int id, string message, Guid relatedActivityId)

And nearly all these methods (barring 1 or 2) has been overridden (all of them are public and just the TraceTransfer calls the WriteLine method, since the msdn blog says that these TraceEvent/Data/Transfer methods internally call Write/WriteLine methods) by the author of the custom trace listener (in the very first link from codeproject.com). I want to test this custom listener to see how it behaves. But in real life I don't know how would the trace source call those TraceEvent (with multiple overloads) and TraceTransfer() methods to trace through the custom listener. Though I do know that I can create an instance of trace source as

TraceSource ts = new TraceSource("myApp");
ts.Listeners.Add(new DBTraceListener);

and add custom listener to it (as in the code above) but the question remains in that how would trace source call TraceEvent/TraceTransfer methods (written in DBTraceListener) to trace through the custom listener.

In other words I don't know how to use this custom listener in my application to log traces. Any help will be greatly appreciated.


An easy way to add a trace listener is using Trace.Listeners.Add() . For example, to add a TextWriterTraceListener :

var listener = new TextWriterTraceListener("e:blah.txt");
Trace.Listeners.Add(listener);
Trace.AutoFlush = true;
Trace.WriteLine("Test!");
链接地址: http://www.djcxy.com/p/52398.html

上一篇: 如何获取从.net中发送跟踪日志的方法和类的名称

下一篇: 如何使用自定义跟踪侦听器记录.net中的痕迹