log stdout/stderr of the gnuplot process

This commit is contained in:
ahr
2017-12-16 19:19:35 +01:00
parent 04b029e1be
commit a359652f8b

View File

@@ -1,10 +1,16 @@
package org.lucares.recommind.logs;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -20,6 +26,10 @@ public class Gnuplot {
private static final String PROPERTY_GNUPLOT_HOME = "gnuplot.home";
private final Path tmpDirectory;
// This would be bad style if this code was executed in a web-container, because it would cause a memory leak.
// But this code is only (and will only) be executed as standalone application.
private static final ExecutorService POOL = Executors.newCachedThreadPool();
public Gnuplot(final Path tmpDirectory) {
this.tmpDirectory = tmpDirectory;
}
@@ -33,15 +43,18 @@ public class Gnuplot {
LOGGER.debug(gnuplotFileContent);
final File gnuplotFile = File.createTempFile("gnuplot", ".dem", tmpDirectory.toFile());
//Files.write(gnuplotFileContent, gnuplotFile, StandardCharsets.UTF_8);
Files.asCharSink(gnuplotFile, StandardCharsets.UTF_8).write(gnuplotFileContent);
final long start = System.nanoTime();
try {
final ProcessBuilder processBuilder = new ProcessBuilder(gnuplotBinary(), gnuplotFile.getAbsolutePath());
processBuilder.inheritIO();
final ProcessBuilder processBuilder = new ProcessBuilder(gnuplotBinary(), gnuplotFile.getAbsolutePath())//
.redirectOutput(Redirect.PIPE)//
.redirectError(Redirect.PIPE);
final Process process = processBuilder.start();
logOutput("stderr", process.getErrorStream());
logOutput("stdout", process.getInputStream());
process.waitFor();
} catch (final IOException e) {
if (e.getMessage().contains("No such file or directory")) {
@@ -56,6 +69,22 @@ public class Gnuplot {
METRICS_LOGGER.debug("gnuplot: {}ms", (System.nanoTime() - start) / 1_000_000.0);
}
private void logOutput(final String humanReadableType, final InputStream stream) throws IOException {
POOL.submit(()->{
try{
final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
String line;
while(( line = reader.readLine()) != null){
LOGGER.info("gnuplot {}: {}", humanReadableType, line);
}
}
catch (Exception e){
LOGGER.warn("Exception while reading "+ humanReadableType+ " of gnuplot command", e);
}
});
}
private String gnuplotBinary() {
if (System.getProperty(PROPERTY_GNUPLOT_HOME) != null) {