Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 761
Matthew Avatar asked Aug 26 '16 15:08

Matthew


People also ask

Which file is used by Logback logging system?

To create a configuration for Logback, you can use XML as well as Groovy. The system will automatically pick up and use the configuration automatically, as long as you're adhering to the naming convention. There are three valid standard file names you can choose from: logback-test.

Is Logback better than log4j?

Key Difference Between Log4j vs LogbackAs logback is improved, version log4j and versions log4j2 and logback have no difference in terms of performance or any features. Therefore log4j is the most used logging utility before the logback newer versions were invented.


2 Answers

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.

like image 52
Augusto Avatar answered Sep 19 '22 03:09

Augusto


The sysout-over-slf4j solutions answers the question 100%.

Just take note: If you setup the Java Util Logger -> SLF4j bridge (jul-to-slf4j), all the System.out.println messages will also be in you logback log file, along with all the messages printed to the Java util logger.

Here is how to set it up: https://stackoverflow.com/a/43242620/2359435

like image 20
Max Avatar answered Sep 20 '22 03:09

Max