asd
asd

Reputation: 1

How to log into a string? Is there a way to capture every console output into a single string?

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?

Upvotes: 0

Views: 734

Answers (1)

Programmer
Programmer

Reputation: 813

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!!!

Upvotes: 1

Related Questions