Any way to turn on/off a println in java (verbose mode)

1.1k Views Asked by At

Is there any way in Java that you can make a println appear only when requested, not by default? Basically something similar to using "-v" in many programs to give you verbose mode, with information on what is happening.

For example let's say I have an if statement in a loop, and a simple println that tells me whether the if statement evaluates to true for each iteration of the loop. Is there any other way to toggle on/off it's visibility other than commenting it out when I don't need it and uncomment it when I do? Then saving it, recompiling it, etc.

It would make it a lot easier to see what is going on in my program, but only when I want that much info. As I said, I am basically looking for a way to implement a "verbose" mode that shows print statements, without having to comment/uncomment save, recompile, etc. Does Java have anything like this?

2

There are 2 best solutions below

0
On

Your best choice is to use an appropriate logger of some kind (log4j for example).

If that's not possible, you can "consume" the stdout and stderr using something like...

PrintStream nullPrintStream = new PrintStream(new OutputStream() {
    @Override
    public void write(int b) throws IOException {
    }
});
System.setErr(nullPrintStream);
System.setOut(nullPrintStream);

Which prevent ALL output from begin printed. You can use a proxy process (using the current stdout wrapped in a proxy PrintStream) to filter the content if that's more appropriate...

0
On

No sysout cannot be turned off using a flag. The functionality you are looking for is provided by loggers such as lo4j. Using a logger, you can use the ConsoleAppender and always set a log level.