Intercept System.out and Date Add Time in Java

Is it possible to intercept calls in System.out.print * and System.err.print * (in Java) and add a timestamp to them? Don’t worry, we use the usual logging frameworks, but sometimes some sys.out leak out, and it would be nice to know when this happens so that we can attach it to the corresponding log files.

+4
source share
3 answers

Can you do this.

See documents

Reassigns the "standard" output stream. First, if there is a security manager, its checkPermission method is called with RuntimePermission ("setIO") permission to check if the "standard" output stream can be reassigned.

public class CustomPrintStream extends PrinterStream{ //override print methods here } System.setOut(new CustomPrintStream()); 
+7
source

It should be possible.

System.out is printStream .

you can expand the stream to add date and time to the printing methods and use System.setOut () to set the stream accordingly.

As a late thought, if you want to determine where print statements come from, you can use: Thread.currentThread().getStackTrace()[1].getClassName();

+2
source

You can use Aspect Oriented Programming to achieve this - in particular AspectJ .

The idea is that you define pointcuts that correspond to the points in your code, and then write advice that runs at those points. The AspectJ compiler is then interwoven in your tips at these points.

So, for your problem, you first define a pointcut that is selected every time you call the print method on PrintStream

 pointcut callPrint(PrintStream ps, String s) : call(* java.io.PrintStream.print*(..)) && target(ps) && args(s); 

Then you could write advice that would go around this call to replace the argument if PrintStream is System.out (you can do the same with System.err .

 void around(PrintStream ps, String s) : callPrint(ps,s) { if(ps.equals(System.out)){ String new_string = ... proceed(new_string); } else proceed(s); } 

Then you need to put all this into an aspect and twist it into your code - there are many tutorials on the Internet on how to do this.

+1
source

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


All Articles