Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 297
Salman A. Kagzi Avatar asked Mar 31 '11 11:03

Salman A. Kagzi


People also ask

What is written output?

Written output disorders are a type of learning disability that result in poor writing skills which lead to a student performing significantly below what is normal when considering the students age, intelligence, and level of education.

What does Write-host do?

Starting in Windows PowerShell 5.0, Write-Host is a wrapper for Write-Information This allows you to use Write-Host to emit output to the information stream. This enables the capture or suppression of data written using Write-Host while preserving backwards compatibility.


1 Answers

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.

like image 56
Salman A. Kagzi Avatar answered Oct 01 '22 21:10

Salman A. Kagzi