I am in a somewhat advanced project written in Java where I have used console messages a lot. I would not like to remove them, but I would not like them to be printed either if I do not define it that way in some configuration option of the program (for example, run it in debugging 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 I have named the instance and a function as SystemOut.println()
) but I would like to override System.out.println("")
it so as not to modify the code that I already have defined and also catch exceptions immediately. Is this possible? I am open to recommendations.
It is possible to change the PrintStream that the System class uses to write the messages. See System.setPrintStream() documentation
Example
Departure:
Redirect to a file
You can create the PrintStream to write directly to a file:
And finally, the recommendation is to use a logger from the beginning of development, with that you have control over the way of logging (Change destination, level of detail, message format, etc.) without changing the code.