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);
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With