Can you overwrite System.out.println ("") ;?


I am in a project written in Java somewhat advanced where I have used a lot of messages by console. I would not like to remove them, but not to print them if I do not define it that way in any configuration option of the program (For example, run it in debug mode).

What I want is to direct them to my own "message console" where I can manipulate this information (Show on screen, create logs, etc). Currently I have a function that simulates the structure (A class that calls the console and have named the instance and a role as SystemOut.println() ) but I would like to overwrite System.out.println("") non modify the code that I have defined and also capture so immediately the exceptions. Is this possible? I am open to recommendations.

asked by Angel 31.07.2017 в 16:24

1 answer


It is possible to change the PrintStream that the System class uses to write the messages. See the documentation System.setPrintStream ()


PrintStream myStream = new PrintStream(System.out) {
    public void println(String x) {
        super.println(System.currentTimeMillis() + ": " + x);
System.out.println("Hola mundo!");


1420553422337: Hola mundo!

Redirect to a file

You can create the PrintStream to write directly to a file:

File file = new File("C:\a.txt");
PrintStream ps = new PrintStream(file);
System.out.println("To File");

And finally, the recommendation is to use a logger from the beginning of development, with that you have control with the form of logging (Change destination, level of detail, message format, etc.) without changing the code.

answered by 31.07.2017 / 16:39