Search This Blog

Friday, March 16, 2012

Debug.writeline

One of the class in .Net that is very useful to log messages or track the sequence of execution is to use 'System.Diagnostics.Debug' class. The Debug.Writeline("Message") writes the message to the output window while debugging. If you want this message to be written to a file then you need to have listener that listens to these messages which is better understood by the below example of code.

Place this code in a button click of windows application. This code is applicable only for vb.net.

    Dim Tr As TextWriterTraceListener
    Tr = New TextWriterTraceListener(System.IO.File.CreateText("Output.txt"))
    Debug.Listeners.Add(Tr)
    Debug.WriteLine("Test Message")
    Tr.Flush()
    Tr.Close()
    Tr.Dispose()


Declares a new TexWriterTraceListener that will create a new text file. Add this listener to the Debug class and start writing the messages. Then flush the buffer of listener and close and dispose the trace. The output.txt file should be placed in the debug folder of your application.

You can also use the Debug class to write the message on conditional basis. For example use:

Dim quantity as integer = 51
Debug.WritelineIf(quantity > 50, "This message will appear")
Debug.WritelineIf(quantity < 50, "This message will NOT appear")

There is one more method called 'Assert' that will display the message only if the evaluated condition returns false. For example:

Dim quantity as integer = 51
Debug.Assert(quantity > 50 "This message will not appear") 
Debug.Assert(quantity < 50 "This message will appear since the quantity < 50 is false")

For better readability, use Debug.Indent() method to indent subsequent messages. You can also use Debug.UnIndent() method to UnIndent subsequent messages.

Debug.Write() appends the message to the same line, while Debug.Writeline() writes the message to a new line.

At last, you can also use Trace.Writeline instead of Debug.Writeline. Both classes send messages to all the listeners in the debug mode. However, in release mode, only Trace.Writeline works.


No comments:

Post a Comment