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

TrustedCreeper

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.

icza

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

System out println

From Java

Overriding System.out.println

From Dev

Error in System.out.println

From Dev

Overriding System.out.println

From Dev

System.out.println - Java

From Dev

System.out.println(); and System.err.println(); printing interchangeably

From Dev

JUnit test for System.out.println/System.err.println

From Dev

java difference between system.out.println() and println()

From Dev

How to test System.out.println(); by mocking

From Dev

System.out.println vs PrintWriter

From Dev

Why is System.out.println bad?

From Dev

Integer in System.out.println - unboxing or toString()?

From Dev

Find the location in code of a system.out.println

From Dev

What is the meaning of ()->System.out.println("done")?

From Dev

Creating a border with System.out.println()

From Dev

Passing System.out.println(); as an argument in a method

From Dev

java reflection System.out.println

From Dev

System.out.println and String arguments

From Dev

Writing System.Out.Println into text file

From Dev

Why is my System.out.println not executing?

From Dev

Unknown output by System.out.println

From Dev

Eclipse | code template for System.out.println()

From Dev

System.out.println print at the same time

From Dev

Unexpected outcome with System.out.println

From Dev

Is there a shortcut for System.out.println on Netbeans?

From Dev

Is there a shortcut for System.out.println on Netbeans?

From Dev

volatile with System.out.println() in Java

From Dev

Shorter version of Java System.out.println()

From Dev

Passing System.out.println(); as an argument in a method