Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the location in code of a system.out.println

Lets say I'm working in a very large project, and have noticed an empty print line, so I'm assuming there is a System.out.println(""); located somewhere in the code. How would I go about trying to figure out where it is, short of just searching the entire project for all occurrences of System.out.println?

like image 358
Lexxicon Avatar asked Sep 07 '14 15:09

Lexxicon


2 Answers

You could implement your own PrintStream and use System.setOut to replace the default stdout. Then either put a debugging marker inside the class (if an empty string is printed), or print out the method name through the call stack (throw and catch an exception and get the stack information).

like image 116
Kayaman Avatar answered Oct 05 '22 22:10

Kayaman


If you're using Java 8+, Durian has a StackDumper class which makes it easy to find where a given line is being printed:

StackDumper.dumpWhenSysOutContains("SomeTrigger")

When "SomeTrigger" is printed, this will get dumped to System.err:

+----------\
| Triggered by SomeTrigger
| at package.MyClass.myMethod(MyClass.java:62)
| (the rest of the stacktrace)
+----------/

For your case (looking for an empty string), it's a little more complicated:

PrintStream sysOutClean = System.out;
StringPrinter sysOutReplacement = new StringPrinter(StringPrinter.stringsToLines(line -> {
    if (line.isEmpty()) {
        StackDumper.dump("Found empty line");
    }
    sysOutClean.println(line);
}));
System.setOut(sysOutReplacement.toPrintStream());

Now if there's something like this:

System.out.println("ABC");
System.out.println("123");
System.out.println("");
System.out.println("DEF");

Then your console will look like this:

ABC
123
+----------\
| Found empty line
| at package.MyClass.myMethod(MyClass.java:62)
| (the rest of the stacktrace)
+----------/

DEF
like image 25
Ned Twigg Avatar answered Oct 05 '22 23:10

Ned Twigg