Search code examples
javaclassloggingconsoletelnet

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?


Solution

  • 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();
            }
        };