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

♀尐吖头ヾ 提交于 2019-12-08 11:33:46

问题


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?


回答1:


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...




回答2:


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.



来源:https://stackoverflow.com/questions/18325335/any-way-to-turn-on-off-a-println-in-java-verbose-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!