How to Trace via category?
.NET lets you add trace statements to code. You c开发者_开发百科an use
Trace.WriteLine"(Some message");
and then define a trace listener to collect those messages to a log file. OK so far.
But you can also do:
Trace.WriteLine"(Some message", "Category");
How can you set up a filter in app.config
(ie <program>.exe.config
) so that only messages with a certain value of "Category" are sent to a listener. The documentation hints that you can do this but falls short of telling you how, I think! I want to define my own categories (by subsystem) and be able to route trace to various log files when needed.
(Yes I know all about log4net and how that can solve all my problems).
You will need to code an implementation of TraceFilter
to filter traces by the category string. Otherwise, you could use the TraceEvent
method and then use EventTypeFilter
to filter traces based on the TraceEventType
.
To modify filters, you use the app.config
file as described in the example for the EventTypeFilter
.
Just to clarify a thing here.
a line like this won't work:
Trace.Listeners["listener2"].Filter = new CategoryFilter("FooFilter", new List<string>(), CategoryFilterMode.DenyAllExceptAllowed);
Because you can't assign a CategoryFilter to a TraceFilter. Type incompatibility. The intention here (in the OP) seems like trying to accomplish this. -- Which, when you look at the app.config, seems possibly doable, but the type incompatibility is more clear when coding programmatically.
To complicate the issue, and maybe the original point of confusion in the MS Doc, is that a LogSource can have a TraceListener, but a TraceListener cannot have a CategoryFilter. The types go only one way, and looks like Trace has to be at the bottom of a "used-by" relationship with respect to the rest of the logging framework in EntLib.
Following on to Jeff's answer with reference to TraceEvent, I've successfully used TraceSource to set up fairly granular filtering. Trace can only do what you ask if you write custom filters, etc, but TraceSource can provide what you need pretty much out of the box. Mike's post gave me clarity on how switches, listeners, and filters all work together with TraceSource to filter effectively.
精彩评论