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);
}
});
}
I haven't tried this yet, but what happens when one does this and then configures SLF4J to use ConsoleAppender?
ReplyDeleteIt is not clear, where to put the code snippet.
ReplyDelete