beryx / text-io

A library for creating interactive console applications in Java
http://text-io.beryx.org/
Apache License 2.0
342 stars 45 forks source link

How to print also to log? #36

Closed cdprete closed 2 years ago

cdprete commented 2 years ago

Hi. Is there a way to redirect all the output also to a Logger?

siordache commented 2 years ago

Text-IO has no support for this, but you can try this: https://stackoverflow.com/a/1370033

siordache commented 2 years ago

The above trick works only with a SystemTextTerminal. A better solution is this one:

public class Main {
    private static final Logger logger =  LoggerFactory.getLogger(Main.class);

    public static class LoggerTerminal implements TextTerminal<LoggerTerminal> {
        private final TextTerminal delegateTerminal;

        public LoggerTerminal(TextTerminal delegateTerminal) {
            this.delegateTerminal = delegateTerminal;
        }

        @Override
        public String read(boolean masking) {
            String s = delegateTerminal.read(masking);
            logger.info(s);
            return s;
        }

        @Override
        public void rawPrint(String message) {
            delegateTerminal.rawPrint(message);
            if(!message.trim().isEmpty()) logger.info(message);
        }

        @Override
        public void println() {
            delegateTerminal.println();
        }

        @Override
        public TerminalProperties<LoggerTerminal> getProperties() {
            return delegateTerminal.getProperties();
        }
    }

    public static void main(String[] args) {
        TextTerminal terminal = new LoggerTerminal(TextIoFactory.getTextIO().getTextTerminal());
        TextIO textIO = new TextIO(terminal);

        String name = textIO.newStringInputReader().read("Welcome, please enter your username:");
        System.out.println("Your name is: " + name);
        textIO.newStringInputReader().withMinLength(0).read("Press enter to exit...");
        textIO.dispose();
    }
}
siordache commented 2 years ago

I edited the above code to also log the input and to not log blank lines in rawPrint.

cdprete commented 2 years ago

I'll have a look at it, but at first glance it looks ok