I'm trying to create a tracing system for my application. I want to
create a new type of Switch that is basically TraceSwitch with an
extra attribute called "includeMethodName". So my application's config
file should look like this, for example:
<configuration>
<system.diagnostics>
<switches>
<add name="FirstSwitch" value="1" includeMethodName="1" />
<add name="SecondSwitch" value="1" includeMethodName="1" />
</switches>
</system.diagnostics>
</configuration>
The help on the Switch class is a little sparse, but from what I can
tell this should be good enough to create a simple derived switch
class:
internal class StackFrameTraceSwitch : TraceSwitch {
private const string INCLUDE_METHOD_NAME_ATTRIBUTE =
"includeMethodName";
private bool m_IncludeMethodName;
public StackFrameTraceSwitch(string displayName, string
description)
: base(displayName, description)
{
}
protected override string[] GetSupportedAttributes() {
return new string[] { INCLUDE_METHOD_NAME_ATTRIBUTE };
}
public override string ToString() {
return String.Concat
(
DisplayName,
" (",
Level.ToString(),
", ",
IncludeMethodName ? "Method Names" : "No Method
Names",
")"
);
}
public bool IncludeMethodName {
get {
foreach (DictionaryEntry entry in Attributes) {
if
(entry.Key.ToString().Equals(INCLUDE_METHOD_NAME_A TTRIBUTE,
StringComparison.OrdinalIgnoreCase)) {
string value = entry.Value.ToString();
if (value.Equals("true",
StringComparison.OrdinalIgnoreCase) ||
value.Equals("1",
StringComparison.OrdinalIgnoreCase) ||
value.Equals("yes",
StringComparison.OrdinalIgnoreCase)
)
{
m_IncludeMethodName = true;
}
}
}
return m_IncludeMethodName;
}
}
}
Problem is it won't read my custom attribute properly. If you paste
the following lines into a program and execute them
StackFrameTraceSwitch sessionSwitch = new StackFrameTraceSwitch
("FirstSwitch", "The 1st switch.");
StackFrameTraceSwitch handlerSwitch = new StackFrameTraceSwitch
("SecondSwitch", "The 2nd switch.");
you find that the includeMethodName attribute is read properly for the
first (i.e. the first one in the .config file) only. If you swap the
order of the <add ...lines in the config file then the first one is
still read properly, and the 2nd is still wrong, proving that it seems
to be dependent on the order of the lines in the file.
I can't be sure, but it looks like the Switch class's implementation
of custom attributes is not reading anything after the first switch.
You can see this in the debugger for the 2nd switch - the Attributes
property is an empty collection when it tries to iterate over it in
the IncludeMethodName property.
--
Philip Daniels