public static Entry<String, String> grabConsoleOutputAndError(Runnable f) {
        ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
        ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
        PrintStream out = new PrintStream(outBuf);
        PrintStream err = new PrintStream(errBuf);
        PrintStream out0 = System.out;
        PrintStream err0 = System.err;

        System.setOut(out);
        System.setErr(err);
        try {
            f.run();
        } finally {
            System.setOut(out0);
            System.setErr(err0);
        }
        out.flush();
        err.flush();
        return new SimpleImmutableEntry<>(outBuf.toString(), errBuf.toString());
    }
Capture both the console output and console error during the execution of the provided function.
tools/src/test/java/org/apache/kafka/tools/ToolsTestUtils.java