javasystem.out

Intercept System.out and prepend date time in Java


is it possible to intercept calls to System.out.print* and System.err.print* (in Java) and prepend a time stamp to them? Don't worry, we use the usual logging frameworks, but occasionally some sys.out leaks out and it would be nice to know when it happen so we can tie it up to the proper log files.


Solution

  • You can do it.

    See the docs

    Reassigns the "standard" output stream. First, if there is a security manager, its checkPermission method is called with a RuntimePermission("setIO") permission to see if it's ok to reassign the "standard" output stream.

    public class  CustomPrintStream extends PrintStream{
    
     //override  print  methods here 
    }
    
    System.setOut(new CustomPrintStream());