Search code examples
javalogginglogbackslf4j

How to redirect System.out to a log file using Logback?


How can I use Logback to capture System.out messages in a Java program?

For example, I would like to use this code:

System.out.println("test: console out to file instead");

... and capture it's output to a file.

Can this be done using the logback.xml config file?


Solution

  • There's a little jar that does this for you: http://projects.lidalia.org.uk/sysout-over-slf4j/index.html

    Please do read the FAQ: http://projects.lidalia.org.uk/sysout-over-slf4j/faq.html - If you use this module and configure logback to output to stdout, you'll get a stream of StackOverFlowErrors :D

    If you want to do this yourself, you need to replace System.out and System.err with a custom PrintWriter (?I cannot fully remember the class name). This custom PrintWriter needs to forward the calls to logback in a semi intelligent manner, as print writters can also print character by character rather than by line.