我可以使用TraceListener在initializeData中添加时间戳吗?

时间:2016-01-04 16:57:18

标签: c# timestamp tracelistener

可以在" initializeData"中添加时间戳。在TraceListener?

这样的事情:

finally {
   if(outStream != null) {
            try {
                outStream.flush();
                outStream.close();
            } catch (IOException e) {
                res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                throw new Exception(e);
            }
}

我想在启动应用程序后将DateTime.Now放在每个日志中。

2 个答案:

答案 0 :(得分: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"));

答案 1 :(得分:1)

这在某种程度上是可能的。 无论你输入什么" 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="MyLog@date.txt"/>
    </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))`;