0

I use the java.util.logging Logger class, and I would like to capture all messages on the console (not just the logs) and put them in a string (that I use later elsewhere). I did find a class that captures the println-s from System.out, but the logs go to System.err so I have to include those as well somehow. I have tried to capture both of them, but I didn't find a way. I also tried to use handlers but I couldn't figure them out. How can I solve this problem? Is there a way to capture every console output into a single string?

2
  • 1
    sounds like an XY problem, what exactly are you trying to achieve by doing this? It might be that there is a solution for that, instead of a solution for the problem cause by the other problem. Commented Jan 26, 2021 at 16:55
  • I have to put everything from the console into a json log file, and the class that creates it uses that string. Since then I was asked to let it go and now I am setting up Logback and slf4j. Thank you for your answer :) Commented Feb 3, 2021 at 10:08

1 Answer 1

1

Use System.setOut(PrintStream ps) method, like in this example:

public class Main{
    public static StringBuffer sb;
    public static void main(String[] args) {
        sb = new StringBuffer();
        PrintStream console = System.out;
        System.setOut(new PrintStream(new OutputStream() {
            
            @Override
            public void write(int b) throws IOException {
                Main.sb.append((char)b);
            }
        }));
        System.out.println("Hello World!!!");//Go to the StringBuffer
        System.out.println("Hello World!!!");//Go to the StringBuffer
        console.println("Output is:\n" + sb);
    }
}

The output is:

Output is:
Hello World!!!
Hello World!!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.