Phil Carson
Phil Carson

Reputation: 884

How do you programatically set the source switch with System.Diagnostics

I have a situation where I need to capture the trace from System.Workflow.Activities.Rules. Currently I have a custom trace listner configurered like so in code:

    _traceListener = new InMemoryTraceListener();
    System.Diagnostics.Trace.Listeners.Add(_traceListener);

and in the app.config I have the source switch configured like so:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <switches>
      <add name="System.Workflow.Activities.Rules" value="Information"/>
    </switches>
  </system.diagnostics>
</configuration>

This works and I am able to capture the race messages in my custom trace listener. I need the trace information as it is critical to the overall solution and is set at the level required.

But as I need to configure the switch programatically instead of through configuration as its going into a dll for the GAC.

I have tried a number of different things with SourceSwitch and TraceSource but none of them have worked for me.

Edit: In summary I want to programatically configure a switch for an existing source from the .net framework so that I can listen to trace messages.

Upvotes: 1

Views: 1606

Answers (2)

Phil Carson
Phil Carson

Reputation: 884

I have adapted some code that I came across that does something similar. It sets the switch via reflection on a non public method. It isn't best practice, but is there another better way?

 #region Dodgy dodgy hackery. There has to be a better way of doing this ....
 var trace = typeof(System.Workflow.Activities.StateActivity)
                .Assembly
                .GetType("System.Workflow.Activities.WorkflowActivityTrace");

 var rules = trace.GetProperty("Rules", BindingFlags.NonPublic | BindingFlags.Static)
                .GetValue(null, null)
                as System.Diagnostics.TraceSource;

 rules.Switch.Level = System.Diagnostics.SourceLevels.Information;

 rules.Listeners.Clear();
 rules.Listeners.Add(_traceListener);
 #endregion

Upvotes: 3

Thomas Weller
Thomas Weller

Reputation: 59228

I guess you're looking for the TraceSource (MSDN) class and do something like

TraceSource mySource = new TraceSource("MySource");
mySource.Listeners.Add(new InMemoryTraceListener());

Upvotes: 0

Related Questions