2016-01-04 41 views
1

可以在TraceListener的“initializeData”中添加一个时间戳吗?我可以使用TraceListener在initializeData中添加时间戳吗?

事情是这样的:

<sharedListeners> 
     <add name="AppSourceListener" 
     type="System.Diagnostics.DelimitedListTraceListener" 
     initializeData="c:\test%date.csv" 
     traceOutputOptions="ProcessId, DateTime, Callstack"> 
     </add>  
</sharedListeners> 

我愿把DateTime.Now在每个日志,一旦应用程序被启动。

+0

重复。如果您使用TraceXXX方法,答案是肯定的:https://stackoverflow.com/questions/863394/add-timestamp-to-trace-writeline?rq=1 – MatthewMartin

回答

1

从.config文件中这是不可能的。要做到这一点从代码创建TraceListener:

//Remove all existing trace listeners 
while (Trace.Listeners.Count > 0) 
    Trace.Listeners.RemoveAt(0); 
//Add the new one with new file name 
Trace.Listeners.Add(new DelimitedListTraceListener(@"mylogwithdatetime.log")); 
0

这是可能的一种方式。 无论你把“initializeData”放到自定义跟踪监听器的构造函数中。所以,如果你有这样的事情

namespace MyLogger 
{ 
    public class DebugListener :TraceListener 
    { 
     string LogFileName; 
     public DebugListener (string filename) 
     { 
      filename = filename.Replace("@date",DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()); 
      LogFileName = filename; 
     } 
    } 
} 

和配置

<system.diagnostics> 
    <trace autoflush="true" indentsize="4"> 
    <listeners> 
     <add name="dbgListener" type="MyLogger.DebugListener,MyLogger" initializeData="[email protected]"/> 
    </listeners> 
    </trace> 
</system.diagnostics> 

然后你会得到的文件名的东西作为MyLog20173.txt 虽然记住构造函数才会被调用一次,你必须重新启动应用程序来创建一个新的日志,但你可以随时处理你的代码中的逻辑,就像这个每月创建一个新的日志文件的逻辑

//get new log file name every month 
string newFileName = string.Format("{0}_{1}{2}.txt","name",DateTime.UtcNow.Year.ToString(CultureInfo.InvariantCulture),DateTime.UtcNow.ToString("MM", CultureInfo.InvariantCulture))`; 
相关问题