使用TraceListener 自动保存跟踪信息到文件中

最近在编写一个使用遗传算法的程序,想跟踪一些中间变量,把它的值写到文件中,但是又不想在算法中加入新的函数来做这种事情,后来想到用TraceListener来保存。通过配置应用程序配置文件app.config,然后在代码中使用Trace.Listeners["myListener"].Write 写跟踪信息,该信息就会被自动记录到文件中去。

配置文件:
< configuration >
< system .diagnostics >
    
< switches >
        
< add  name ="MagicTraceSwitch"  value ="3"   />
    
</ switches >
    
< trace  autoflush ="false"  indentsize ="4" >
        
< listeners >
           
< add  name ="myListener"  type ="System.Diagnostics.TextWriterTraceListener"  initializeData ="c:\myListener.log"   />
           
<!--  You must supply a valid fully qualified assembly name here.  -->  
           
< remove  type ="Assembly text name, Version, Culture, PublicKeyToken" />  
        
</ listeners >
    
</ trace >
</ system.diagnostics >
 
</ configuration >

在listeners 配置节里面的<add .../>中的type是要使用的监听器的类,initializeData是要保存的文件路径。
.NET Framework 1.1自带了几种监听器,但是你可以自己扩展监听器的类型,将调试信息保存到其他地方,如数据库中(类似于net4log)。

在程序代码中的用法:
for ( iter  =   0 ; iter  <  MAX_ITER; iter ++  )
            
{
                
if( iter % 300 == 0 )
                
{
                    sppGA.Scale 
*= 0.1;
                }

                
for(int i = 0; i < 10; i++ )
                
{
                    sppGA.CrossOver();
                }

                sppGA.Mutation();
                sppGA.Mutation();
                sppGA.Mutation();
                sppGA.Memory();
                System.Diagnostics.Trace.Listeners[
"myListener"].Write(((Node) sppGA.Individuals[sppGA.Best]).Variables.Transpose().ToString());
                Console.WriteLine(
"Iter:{0} Fitness:{1} Best:{2} Worst{3} Scale:{4} ",iter,((Node) sppGA.Individuals[sppGA.Best]).Fitness,sppGA.Best,sppGA.Worst,sppGA.Scale);
            }





你可能感兴趣的:(listener)