TraceListener in win32 application?

  • Thread starter Thread starter John Batdorf
  • Start date Start date
J

John Batdorf

Ugh. I obviously don't understand the correct way to use this thing!
I have several #if(DEBUG) code blocks to write to a file ErrorLog.txt
to troubleshoot why and what exceptions are being encountered.

So in my class this is defined:

static FileStream traceLog = new FileStream("ErrorLog.txt",
FileMode.OpenOrCreate, FileAccess.Write);

static TextWriterTraceListener traceListener = new
TextWriterTraceListener(traceLog);

then in the same class I have this method

private static void Logger(string errorMessage)
{
// Create a text file to write messages to
// Create a TextWriterTraceListener
//TextWriterTraceListener traceListener = new
TextWriterTraceListener(traceLog);
// Add the traceListener to the Trace.Listeners collection
Trace.Listeners.Add(traceListener);
Trace.WriteLine(errorMessage);
//Trace.Listeners.Remove(traceListener);
Trace.Flush();
}

At various places in my program... I make this call:

Logger("Exception thrown from Logout()");
Logger(ex.Message.ToString());

And here's the problem! My file, the first time Logger is called no
problem errorMessage is written to the file.
the second time it's called, it creates two entries of the
errorMessage to the file. The third time... you get the point.

Here's a sample file: (each of the items only happened once, but was
written multiple times)
MAILSERVER=someconfigfilesetting
Connection Made
Connection Made
Login Success
Login Success
Login Success
MailCount = 0
MailCount = 0
MailCount = 0
MailCount = 0


Ideas? I can't figure out why this is happening... when stepping into
the debugger, I don' see this data replicated, and I'm not seeing it
written duplicate
 
John Batdorf said:
Ugh. I obviously don't understand the correct way to use this thing!
I have several #if(DEBUG) code blocks to write to a file ErrorLog.txt
to troubleshoot why and what exceptions are being encountered.

So in my class this is defined:

You only add the TraceListener once.
If you add it a second time, then Trace.WriteLine will call it twice.

Looks like this is really a code organization problem. You need to run some
setup code before you static methods will work. You need a static
constructor:


class MyType()
{
static MyType()
{
System.IO.StreamWriter sw =
new
System.IO.StreamWriter("Errors.txt",false,System.Text.Encoding.ASCII);
sw.AutoFlush = True;
TextWriterTraceListener tl = new TextWriterTraceListener(sw);
Trace.Listeners.Add(tl);
}


private static void Logger(string errorMessage)
{
Trace.WriteLine(errorMessage);
}

}


David
 
Thanks I realized this, and actually ended up implementing a different
way, but I really appreciate the quick responses.
 
Back
Top