A couple of days ago I was struggling with a 3rd party API. Didn’t have access to the source code and the library was dumping out debug messages to the console via System.out.println(). I prefer Log4J and I was having a hard time figuring out which message from my logs corresponded to messages from the 3rd party API.
Anyway, I ended up writing a small Java class to redirect all SOP output to my Log4J setup. Works like a charm and is simple to use. Just instantiate the class and you are done. Of course the new object should be created only after the Log4J system has been initialized.
In case the Log4J system is setup to use a ConsoleAppender, we must make sure that the Follow option is set to False. If it is left as true, ConsoleAppender will also send output to the System.out stream which we are redirecting back to Log4J! In effect we will allow an infinite loop, resulting in a Stack Overflow. To avoid this we look for a ConsoleAppender in the list of appenders and then check if the Follow option has been set to true. If so we reset it to false and reinitialize the ConsoleAppender.
That’s it. Nothing more to do.
Released under the Apache 2.0 license.