4

I start a process with ProcessBuilder and want to write the output to log4j. How can I achieve this?

I know that I can redirect the output of the process to a File and then read that File back, but I hope there is some easier way.

I would like to avoid to write my own OutputStream implementation if there is a simpler solution. I hope that I am not the first who would like to get the output of a ProcessBuilder as a "good java object" like a

 List<String> 

or something else which is easy to handle.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
  • Possible duplicate of [Log4J: How do I redirect an OutputStream or Writer to logger's writer(s)?](http://stackoverflow.com/questions/6995946/log4j-how-do-i-redirect-an-outputstream-or-writer-to-loggers-writers) – A_Di-Matteo Feb 25 '16 at 13:23
  • It is not a real duplicate. The referenced question redirects an OutputStream, this question asks how to write process output, which is retrieved via InputStreams first. – Queeg Jul 11 '23 at 22:03

1 Answers1

1

You can use Process.getInputStream() and/or Process.getErrorStream() to retrieve output and write that to log4j. For example:

private static final Logger LOG = Logger.getLogger(MyClass.class);
....
ProcessBuilder pBuilder = new ProcessBuilder("MyProcess").redirectErrorStream(true);
Process process = pBuilder.start();
LOG.info(new String(IOUtils.toByteArray(process.getInputStream())));

If it's a process that runs a long time and occasionally provides output, then it's better to put the last line in a separate thread.

THelper
  • 15,333
  • 6
  • 64
  • 104
  • Greetings, would you mind to add the import for the `IOUtils`? There are many libraries that use the same class name. Thank you. – acarlstein Oct 19 '22 at 16:47