.net 如何在app.config中定义自定义TraceListener

.net 如何在app.config中定义自定义TraceListener,.net,configuration,exception-handling,trace,trace-listener,.net,Configuration,Exception Handling,Trace,Trace Listener,我已经实现了一个自定义跟踪侦听器(源自TextWriteTraceListener),现在我想将我的应用程序设置为使用它,而不是使用标准的TextWriteTraceListener 首先,我添加了defaultTextWriteTraceListener,以确保它正常工作。这是我的app.config: <configuration> <system.diagnostics> <trace autoflush="true" indentsi

我已经实现了一个自定义跟踪侦听器(源自
TextWriteTraceListener
),现在我想将我的应用程序设置为使用它,而不是使用标准的
TextWriteTraceListener

首先,我添加了default
TextWriteTraceListener
,以确保它正常工作。这是我的app.config:

<configuration>
    <system.diagnostics>
        <trace autoflush="true" indentsize="4">
            <listeners>
                <add name="TextListener"  type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log" />
            <remove name="Default" />
            </listeners>
        </trace>
    </system.diagnostics>
</configuration>
但是,现在当我尝试记录某些内容时,我会收到一个
ConfigurationErrorsException
,其中包含以下消息:

找不到MyApp.Utils.FormattedTextWriterTraceListener类的类型


有人知道如何在配置中设置此自定义侦听器吗?如果可能的话?

也可以尝试指定程序集,如下所示:

<configuration>
    <system.diagnostics>
        <trace autoflush="true" indentsize="4">
            <listeners>
                <add name="TextListener" 
                    type="MyApp.Utils.FormattedTextWriterTraceListener, MyApp"
                    initializeData="trace.log" />
            <remove name="Default" />
            </listeners>
        </trace>
    </system.diagnostics>
</configuration>

我最近一直在努力解决这个问题,以防万一它对任何人都有帮助

我知道我的类型存在,所以我写了以下内容:

Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof("yourclassname"));
Type myClassType = assembly.GetType("yournamespace.yourclassname");
在我的例子中,myClassType.AssemblyQualifiedName在type属性中包含我在app.config文件中需要的字符串

例如:



程序集名称是
MyApp
,我在类型参数中添加了一条不同的消息(相同的异常类型)`无法创建MyApp.Utils.FormattedTextWriterTraceListener,MyApp。现在他找到了类型,但无法创建实例,可能是构造函数或其他调用的方法中存在异常,尝试在costructor和debug中设置断点对我来说,是因为我忘记重写一些基本构造函数。请记住,在出现的intellisense 4中,基本构造函数-当按下向下箭头时,还有两个很容易被忽略。如果你到了这里,但仍然没有让它工作(我没有),就像@user3141326建议的那样,为
公共CustomTraceListener(字符串名称):base(名称)提供构造函数重写{}
。其他的可以省略。
Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof("yourclassname"));
Type myClassType = assembly.GetType("yournamespace.yourclassname");
<system.diagnostics>
    <sources>
      <source name="System.ServiceModel" switchValue="Information,ActivityTracing" propagateActivity="true">
        <listeners>
          <add name="CircularTraceListener" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="CircularTraceListener" type="Microsoft.Samples.ServiceModel.CircularTraceListener, CircularTraceListener, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
           initializeData="C:\MyWebService\APILog\CircularTracing-service.svclog" maxFileSizeKB="1000" />
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>