1

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.

Phil Carson
  • 884
  • 8
  • 18

2 Answers2

3

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
Phil Carson
  • 884
  • 8
  • 18
  • this is an awesome approach(hacky yes, but still) i'm attempting the same with SignalR, but the traces are instance properties inside, so i may need to locate the instantiated TraceSources. So this solution is close, but not always enough – Jody Sowald Jun 04 '21 at 16:08
0

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

TraceSource mySource = new TraceSource("MySource");
mySource.Listeners.Add(new InMemoryTraceListener());
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • 1
    This didn't work for me. I thought that you would use a TraceSource when you were writing trace messages in your code rather than listening to trace messages coming from a .net framework source? – Phil Carson Dec 05 '14 at 03:05