Reputation: 367
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.
Upvotes: 2
Views: 3847
Reputation: 4255
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="[email protected]"/>
</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";
Upvotes: 1
Reputation: 791
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"));
Upvotes: 2