Is there a way to show line numbers in the Eclipse console?
My intent here is to show in the Eclipse console the file/line number that produced the output, not a se
You can create a custom PrintStream
that inspects the current stack trace and includes file / line numbers in the output. You can then use System.setOut
/System.setErr
to cause all stdout/stderr output to include this information.
By formatting it properly Eclipse will pick it up as stack trace elements and generate links.
Here's a complete demo:
public class Main {
public static void main(String args[]) {
System.setOut(new java.io.PrintStream(System.out) {
private StackTraceElement getCallSite() {
for (StackTraceElement e : Thread.currentThread()
.getStackTrace())
if (!e.getMethodName().equals("getStackTrace")
&& !e.getClassName().equals(getClass().getName()))
return e;
return null;
}
@Override
public void println(String s) {
println((Object) s);
}
@Override
public void println(Object o) {
StackTraceElement e = getCallSite();
String callSite = e == null ? "??" :
String.format("%s.%s(%s:%d)",
e.getClassName(),
e.getMethodName(),
e.getFileName(),
e.getLineNumber());
super.println(o + "\t\tat " + callSite);
}
});
System.out.println("Hello world");
printStuff();
}
public static void printStuff() {
System.out.println("More output!");
}
}
Eclipse Console:
I consider this to be a hack though, and I wouldn't use it for anything but casual debugging.
At first I will rephrase your question in my own words so that you can check if I got your question right: You want to have all console output to be linked to the source code which produced it.
In this case this is NOT possible without using some modifying the standard libraries (System.out and System.err). Such a code would probably use the current stacktrace (see e.g. Is there a way to dump a stack trace without throwing an exception in java?) to determine the code (and line-number) where the print-statement was called. The next step would be to create an eclipse plugin which uses the gathered information to jump to the determined line (or to make eclipse think it is displaying a stacktrace).
You need to add line output to the exception handler.
For example:
...
} catch (Exception e) {
System.out.println(e.getStackTrace()[0].getLineNumber());
}
...
This code will print out the line that caused the exception.