Sunday, October 17, 2010

Redirect stdout to logger

Recently, whilst using an external jar in my project, I found that it was doing a lot of logging to stdout using System.out.print statements. Even exceptions were being printed using e.printStackTrace(). We all know that this is bad practice and we should always consider using a logger instead. It was really annoying, seeing these messages come up on my console. Since my application already uses SLF4J for logging, I decided to redirect stdout and stderr to my logger. The following code snippet shows how:
private static final Logger LOGGER = Logger.getLogger(MyClass.class);

/**
 * Redirects stdout and stderr to logger
 */
public static void redirect(){
 System.setOut(new PrintStream(System.out){
  public void print(String s){
   LOGGER.info(s);
  }
 });
 System.setErr(new PrintStream(System.err){
  public void print(String s){
   LOGGER.error(s);
  }
 });
}

2 comments:

  1. I haven't tried this yet, but what happens when one does this and then configures SLF4J to use ConsoleAppender?

    ReplyDelete