2012-09-25 54 views
0

我已经在具有特定名称的代码中创建了跟踪源,然后我想使用app.config中的部分在运行时将侦听器附加到它。将跟踪侦听器附加到app.config中的现有跟踪源

这里是我的app.config:

<system.diagnostics> 
    <trace autoflush="true"/> 
    <sources> 
     <source name="myTraceSource" 
       switchName="mySwitch" 
       switchType="System.Diagnostics.SourceSwitch" > 
     <listeners> 
      <clear/> 
      <add name="textwriterListener" 
      type="System.Diagnostics.TextWriterTraceListener" 
      initializeData="c:\dev\mylog.txt" 
      traceOutputOptions="ProcessId, DateTime, Callstack" /> 
     </listeners> 
     </source> 
    </sources> 
    <switches> 
     <add name="mySwitch" value="Verbose" /> 
    </switches> 
    </system.diagnostics> 

我可以看到,在代码生成与

this.TraceSource.TraceEvent(TraceEventType.Verbose, 0, p_message); 

的消息,但没有出来,在日志文件(它不是甚至创建)。当我设置一个断点并查看this.TraceSource.Listeners时,它是空的。

任何想法我在这里做错了什么或调试这种事情的任何提示?是否有可能将一个新的侦听器附加到这样的现有源?

我也尝试没有成功如下:

<system.diagnostics> 
    <trace autoflush="true" indentsize="4"> 
    <listeners> 
     <add name="TextListener" 
      type="System.Diagnostics.TextWriterTraceListener" 
      initializeData="c:\dev\mylog.txt" /> 
     <remove name="Default" /> 
    </listeners> 
    </trace> 
</system.diagnostics> 
+0

哈哈,所以原来我是个白痴,有一个'TraceSource.Listeners.Clear()'行中的某处程序启动,它删除了我在配置文件中添加的任何监听器。它现在起作用了,我会继续并接受这个问题的答案。 – WildCrustacean

回答

4

我看到一种可能性是,如果你在配置文件中指定的目录不存在。这就是说你不显示如何初始化TraceSource实例,所以我不确定它不会有什么关系。无论如何,一个简单的控制台应用程序使用你的配置部分工作正常。

class Program 
{ 
    static TraceSource ts = new TraceSource("myTraceSource"); 

    static void Main(string[] args) 
    { 
     ts.TraceEvent(TraceEventType.Verbose, 0, "Hello"); 
    } 
} 

此外,请确保您的app.config是完整的。我以为你只是张贴System.Diagnostics程序部分,但这里是完整的例子:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <system.diagnostics> 
    <trace autoflush="true"/> 
    <sources> 
     <source name="myTraceSource" 
       switchName="mySwitch" 
       switchType="System.Diagnostics.SourceSwitch" > 
     <listeners> 
      <clear/> 
      <add name="textwriterListener" 
      type="System.Diagnostics.TextWriterTraceListener" 
      initializeData="c:\dev\mylog.txt" 
      traceOutputOptions="ProcessId, DateTime, Callstack" /> 
     </listeners> 
     </source> 
    </sources> 
    <switches> 
     <add name="mySwitch" value="Verbose" /> 
    </switches> 
    </system.diagnostics> 
</configuration>