Hook into System.out.println(); and modify
Asked Answered
D

3

6

I would like to modify the output printed by System.out.println();. How is this possible? It is possible - I've seen it in Bukkit/Craftbukkit. If a plugin is printing a string with System.out.println(String string); Bukkit adds a time/date and logging status to the string. I would like to do the same like Bukkit.

Doyon answered 6/1, 2015 at 14:5 Comment(2)
You would be better off designing and implementing your own "print" class and having that used.Carolanncarole
I have my own logger class to log, but my software is a bit like bukkit. Other users can develop plugins for it and when the plugin use the println() method it should have a prefix too. So they can use my logger but they don't have to use it.Doyon
H
15

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.

Hotel answered 6/1, 2015 at 14:9 Comment(0)
C
0
PrintStream print= new PrintStream(System.out) {
    @Override
    public void println(String yourString) {
        super.println(System.currentTimeMillis()+ ": " + yourString);
    }

};

print.println("your String");
Christabella answered 6/1, 2015 at 14:15 Comment(0)
W
0

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.

Whipstall answered 5/2, 2019 at 9:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.