简体   繁体   中英

Redirecting System.out.err does not work

I have the following code:

private void replaceStdIo(SocketChannel socketChannel) throws IOException {
        socketChannel.configureBlocking(blockingMode);
        InputStream in = new RedirectorInputStream();
        PrintStream out = new PrintStream(new RedirectorOutputStream(), false, charsetEncoding);
        System.setIn(in);
        System.setErr(out);
        System.setOut(out);
    }

It is part of a bigger Telnet Class which I use to get Info out of my Server. Current problem is that I have a Logger. I want to output everything of the logger into the Telnet Console, but only System.out.print works. System.err should also work, but for some reason it is not?

This is the Console output in the IDE:

14:06:42:0723.: From ConsoleIn.java -> Found the Commandinput FINEST in 
setDebugLevel(FINEST)
14:06:42:0725.: From Debug.java -> Set debugLevel to FINEST

But this does not get printed out in the Telnet Console on the PC, only everything with System.out. Does anyone have any idea why?

I fixed my issue by creating a new Handler. As it turns out, the old consoleHandler blocked the interception of System.err . By creating my own, new Handler and taking out consoleHandler it ended up working.

The new, working Code:

telnetHandler = new Handler() {
        @Override
        public void publish(LogRecord record) {
            System.err.println(record.getMessage());
        }

        @Override
        public void flush() {
            System.err.flush();
        }

        @Override
        public void close() throws SecurityException {
            System.err.close();
        }
    };

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