Hook into System.out.println(); and modify

丶灬走出姿态 提交于 2019-11-30 20:38:30

You can change the PrintStream that is used as the standard output:

System.setOut(PrintStream out)

Create your own PrintStream implementation which prints whatever extra info you want to the (old) standard output, and set it with:

System.setOut(myStream);

Example:

The following example prints the current time millis before each printed String that is printed with PrintStream.println(String x) method:

PrintStream myStream = new PrintStream(System.out) {
    @Override
    public void println(String x) {
        super.println(System.currentTimeMillis() + ": " + x);
    }
};
System.setOut(myStream);
System.out.println("Hello World!");

Output:

1420553422337: Hello World!

Note:

This example only overrides the PrintStream.println(String x) method, so calling other print methods of PrintStream would not add the time stamp to the output.

kallel firas
PrintStream print= new PrintStream(System.out) {

    @Override

    public void println(String yourString) {

        super.println(System.currentTimeMillis()+ ": " + yourString);

    }

};

print.println("your String");

This question is already answered, however, I would like to add a very good method to trace prints.

PrintStream myStream = new PrintStream(System.out) {
        @Override
        public void println(String line) {
            StackTraceElement element = new Exception().getStackTrace()[1];
            super.println("("+element.getFileName()+":"+element.getLineNumber()+") "+line);
        }
    };

    System.setOut(myStream);

Now when you print something, it will show up like "(File:linenumber) text", and in many editors you can just click on that to jump to the location. Its probably quite expensive to get the stacktrace all the time, so probably best to only use it during debug.

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