2

It is possible to put a timestamp in the "initializeData" on the TraceListener?

Something like this:

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

I would like to put the DateTime.Now in every log, once the application is initiated.

MatthewMartin
  • 32,326
  • 33
  • 105
  • 164
MauroAlexandro
  • 347
  • 3
  • 6
  • 18
  • Duplicate. Answer is yes if you use the TraceXXX methods: https://stackoverflow.com/questions/863394/add-timestamp-to-trace-writeline?rq=1 – MatthewMartin Jan 04 '16 at 20:38

2 Answers2

1

This is not possible from .config file. To do that create TraceListener from code:

//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

That is possible in one way. Whatever you put as "initializeData" goes to the constructor of the custom trace listener. So if you have something like this

public class DebugListener :TraceListener
{
    string inputFilename = null;
    public string LogFileName;
    
    public DebugListener (string filename)
    {
        inputFilename = filename;
        Init();
    }
    
    private void Init()
    {
        LogFileName = inputFilename
        .Replace("@date",DateTime.UtcNow.ToString("yyyyMM"));
    }
}

and the config

<system.diagnostics>
    <trace autoflush="true" indentsize="4">
    <listeners>
        <add name="dbgListener" 
             type="MyLogger.DebugListener,MyLogger" 
             initializeData="MyLog@date.txt"/>
    </listeners>
    </trace>
</system.diagnostics>

Then you will get the filename as something as MyLog20173.txt Although remember the constructor will only be called once and you have to restart the app to create a new log but you can always handle that logic in your code like this one which creates a new log file every month

//get new log file name every month
string newFileName = $"log_{DateTime.UtcNow.ToString("yyyyMM")}.txt";

//get new log file name every day
string newFileName = $"log_{DateTime.UtcNow.ToString("yyyyMMdd")}.txt";
Vinod Srivastav
  • 3,644
  • 1
  • 27
  • 40