Delphi Clinic | C++Builder Gate | Training & Consultancy | Delphi Notes Weblog | Dr.Bob's Webshop |
|
Printing Debug Messages
In the article Assertions in JBuilder, we could see how to use the borland.jbcl.util.Diagnostic class, for inserting assertions in our programs.
But this class contains some more handy methods, we can use for our debugging process.
How often we just want to print a simple value of a variable to the standard output, to see what the value is?
We can implement this by adding a line like this to our program:
System.out.println("DEBUG MESSAGE: Value of variable is " + value);
And when we are done developing and debugging our program, and it is time for the final build, we have to erase all these lines. We can of course create a local boolean variable debugMode, set it to true and check this variable before printing a debug message:
if (debugMode) System.out.println("DEBUG MESSAGE: Value of variable is " + value);And for the final build we set the debugMode variable to false, and the debug messages will not be printed, while the program is running.
But still, that isn't a very nice way of handling debug messages like this. And that is where the Diagnostic class comes in. This class contains three static methods concerned with printing to an output stream. We can even assign a different output stream (e.g. a file, or URL), instead of the standard System.err output stream. And finally: when we compile the final build, we can exclude the Diagnostic class from the build, so every method invokation is excluded.
Here follows a short description of the different methods to print messages:
Diagnostic.printlnc("DEBUG MESSAGE: Value of variable is " + value);
Standard the output of the print methods is sent to System.err. But we can change this with the setLogStream(PrintStream log) method. If for example we want to sent the ouput to a file called log.txt, we would insert the following statement:
Diagnostic.setLogStream(new java.io.PrintStream(new java.io.FileOutputStream("log.txt")));
And finally with one method call we can disable all printing, during developing:
Diagnostic.enable(false);
As described in the Assertions in JBuilder article, we can exclude methods calls of the Diagnostic class, when compiling the program. In short: make sure the Exclude class field of the Compiler tab, in the project properties dialog, contains borland.jbcl.util.Diagnostic.