简体   繁体   English

您如何使用 System.Diagnostics 以编程方式设置源开关

[英]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.我有一种情况需要从 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:在 app.config 中,我将源开关配置如下:

<?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.但是因为我需要以编程方式而不是通过配置来配置开关,因为它会进入 GAC 的 dll。

I have tried a number of different things with SourceSwitch and TraceSource but none of them have worked for me.我用 SourceSwitch 和 TraceSource 尝试了许多不同的东西,但没有一个对我有用。

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.编辑:总而言之,我想以编程方式为 .net 框架中的现有源配置一个开关,以便我可以侦听跟踪消息。

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

I guess you're looking for the TraceSource (MSDN) class and do something like我猜您正在寻找TraceSource (MSDN)类并执行类似的操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM