Koroshiya
Koroshiya

Reputation: 45

Trace listener is not generating log file

I'm supposed to be getting a trace listener file like log.txt (as stated in the book I'm currently reading)

But it's not happening for me. Please tell me how I can fix this?

I've not done anything similar to this in the past.

// Write to a text file in the project folder 
Trace.Listeners.Add(new TextWriterTraceListener(File.CreateText("log.txt")));

// Text writer is buffered, so this option calls Flush() on all 
// listeners after writing
Trace.AutoFlush = true;
Trace.WriteLine("Trace says I'm watching.");

Upvotes: 1

Views: 1424

Answers (2)

Manu
Manu

Reputation: 1

I had a similar issue and needed to add AutoFlush in the correct place/order.

string logFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "mylog.txt");
TextWriterTraceListener logFile = new(File.CreateText(logFilePath));
Trace.Listeners.Add(logFile);
Trace.AutoFlush = true;
Trace.WriteLine("Trace log statement here!");

I am also reading a book and created a console app for the same, and in my case, the file was get generated just fine but the Trace was not visible even after executing the statement.

It turned out the issue was due to my mistake of adding the AutoFlush after the WriteLine statements. When I moved the statement before WriteLine it worked, you can add the AutoFlush statement even before adding a listener as well.

Upvotes: 0

Mong Zhu
Mong Zhu

Reputation: 23732

Please tell how I can fix this.

There is no fixing needed really. The file is created and you message is in there, you are simply looking at the wrong site for the file.

Since you gave only a filename it is going to be in the program working directory, (which can be different from the exe location, even if in most cases they will be the same). But take at first a look at the same folder as the *.exe file is in. If you want the log file to be saved in a specific place you need to define the entire path:

I'm supposed to be getting a trace listener file ,log.txt, (as stated int the book I'm currently reading), but it's not happening for me. Please tell how I can fix this.

I've not done anything related to this in the past.

// Write to a text file in the project folder 
Trace.Listeners.Add(new 
   TextWriterTraceListener(File.CreateText(@"C:\MyLogStorage\log.txt")));

Upvotes: 2

Related Questions