Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

java - Include filename/line number corresponding to System.out.print statements in Eclipse Console

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 serial line numbering of the messages (although that could also be an interesting question).

I am looking for something similar to Chrome's javascript console, where every line has a link that takes you to the function that printed it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 + "at " + callSite);
            }
        });

        System.out.println("Hello world");
        printStuff();
    }

    public static void printStuff() {
        System.out.println("More output!");
    }
}

Eclipse Console:

enter image description here

I consider this to be a hack though, and I wouldn't use it for anything but casual debugging.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...