Capture in System.out.println (); and change

I would like to change the output printed by System.out.println(); . How is this possible? It is possible - I saw it in Bukkit / Hook. If the plugin prints a line with System.out.println (Line String); Bukkit adds the time / date and registration status to the line. I would like to do the same as Bukkit.

+5
source share
3 answers

You can change the PrintStream , which is used as standard output:

System.setOut (PrintStream out)

Create your own PrintStream , which prints any additional information that you want (old) standard output, and set it with:

 System.setOut(myStream); 

Example:

The following example prints the current millimeters of time before each printed String , which is printed using the 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!"); 

Conclusion:

 1420553422337: Hello World! 

Note:

This example only overrides the PrintStream.println(String x) method, so calling other PrintStream printing methods will not add a timestamp to the output.

+13
source
 PrintStream print= new PrintStream(System.out) { @Override public void println(String yourString) { super.println(System.currentTimeMillis()+ ": " + yourString); } }; print.println("your String"); 
0
source

This question has already been answered, however I would like to add a very good method for tracking fingerprints.

 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 type something, it will display as "(File: linenumber) text", and in many editors you can simply click on it to go to the desired location. It is probably sufficient to constantly get the stack trace, so it is probably best to use it only during debugging.

0
source

Source: https://habr.com/ru/post/1210478/


All Articles