Search code examples
javaruntimeexecapache-commonsapache-commons-exec

Writing Output & Error to Log files using PumpStreamHandler


I have been searching for a while to get a good example for writing Process output & error stream to log file. I use apache-commons exec library to execute my process. Following a code sample to demonstrate that

public static int executeCommand(CommandLine command, Logger log) throws ExecuteException, IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);

    PumpStreamHandler psh = new PumpStreamHandler();
    executor.setStreamHandler(psh);

    return executor.execute(command);
}

Solution

  • Following is the code to achieve this.

    class ExecLogHandler extends LogOutputStream {
        private Logger log;
    
        public ExecLogHandler(Logger log, Level logLevel) {
            super(logLevel.toInt());
            this.log = log;
        }
    
        @Override
        protected void processLine(String line, int logLevel) {
            log.log(Level.toLevel(logLevel), line);
        }
    }
    

    This is how we can use the above class.

    public static int executeCommand(CommandLine command, Logger log) throws ExecuteException, IOException {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
    
        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(log, Level.DEBUG), new ExecLogHandler(log, Level.ERROR));
        executor.setStreamHandler(psh);
    
        return executor.execute(command);
    }
    

    Using apache-commons exec like this makes code & life (of a programmer) so simple. I was able to discard a huge amount of code that used Runtime.exec to execute commandline commands.