LWJGL and Logging

In my current project I make heavy use of logging. To be able to customize logging I am using log4j. Unfortunately LWJGL doesn’t use a log framework of any kind and just outputs on the console via System.out.println(). To add these outputs to the logfile or a log4j console appender one has to reroute the output through log4j. Luckily there is a pretty easy way, I found it in a stackoverflow posting. So how does it work? There is a Java API that allows to set a new PrintStream for System.out and System.err:

1
2
System.setOut(PrintStream stream);
System.setErr(PrintStream stream);

So we simply have to add our own PrintStream implementation that calls the logger and we are done:

1
2
3
4
5
new PrintStream(realPrintStream) {
    public void print(final String message) {
        LOG.info(message);
    }
}

LOG would be our log4j Logger.

Leave a Reply