SystemOutRedirectToLog4j is a Java class that redirects all System.out.println() log messages from a Java program to a configured Log4J system running in the same JVM.
Why?
Well, I needed something like this. I was working with a 3rd party Java library and did not have access to the source code. Had to just drop the JARs into the classpath and start using the API. This library use SOP extensively to log messages to the console. I prefer Log4J.
The only problem was that I ended up with two log files. One produced by Log4J and other the dump of the console from the 3rd party API.
And matching the log statements was a pain and very cumbersome, particularly to someone spoiled silly with Log4J”s rich logs patterns. No time stamps! Ecch!
So I wrote this little program to help solve this particular problem. Now I have a single Log file and Log4J controls that. All SOP output is also dumped into this file with the appropriate Log4J log patterns!
Yes! Time stamps in log messages! And messages in the proper sequence!
Download
Download SystemOutRedirectToLog4J source distribution. Version 0.1.
The download package above is a simple ZIP file containing the source code for the "SystemOutRedirectToLog4J" class. To use it, just unzip into you source path and use!
Usage
Using SystemOutRedirectToLog4J is fairly straightforward. All you need to do is instantiate SystemOutRedirectToLog4J after you have initialized your Log4J at runtime. SystemOutRedirectToLog4J will look at your Log4J configuration and make only one change, if required.
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.
To start redirecting SOP calls to the Log4J system, just add the following to your code after you have initialized Log4J.
new SystemOutRedirectToLog4j() ;
That’s it. Nothing more to do.

