Redirect System.out.println() to Log4J

Redirect System.out.println() to Log4J

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.

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.

See the details and download the source code from my web site.

Released under the Apache 2.0 license.

4 thoughts on “Redirect System.out.println() to Log4J

  1. Hey,
    thanks for the article – just what I needed for a problem @ work I have to solve!!!

    btw – are you a fan of ‘Jeeves and Worcester’? – just a hunch guessing at your domain name…

    All the best,
    Rohit

  2. You are welcome Rohit. I am happy you found a use for this.

    You are right about the name of this blog. I am a Wodehouse fan, particularly of the “Jeeves & Wooster” series, with Blandings a close second.

    – Gautam

  3. Hello! This post couldn’t be written any better! Reading through this post reminds me of my old room mate!
    He always kept talking about this. I will forward this article to him.
    Pretty sure he will have a good read. Many thanks for sharing!

Leave a Reply

Your email address will not be published. Required fields are marked *