简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM