Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 490
TrustedCreeper Avatar asked Jan 06 '15 14:01

TrustedCreeper


1 Answers

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.

like image 132
icza Avatar answered Oct 18 '22 00:10

icza