0

I am using IntelliJ and Java. I want to copy the output of the running program to a string. This solution must work both locally in IntelliJ and in a Jenkins job.

For example, my running console output looks like this:

log4j:ERROR Could not find value for key log4j.appender.stdot

log4j:ERROR Could not instantiate appender named "stdot". log4j:ERROR

Could not find value for key log4j.appender.stdout log4j:ERROR Could
not instantiate appender named "stdout". [1;34m2019-05-12 08:17:38
Property file env/application.properties parsed successfully[0m

I want to copy all of this log to a string. I've tried numerous solutions but none of them have worked.

cbryant02
  • 583
  • 4
  • 16

1 Answers1

0

You could use System.setOut() with a StringWriter.

For example:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
System.setOut(new PrintStream(stream));
String output = stream.toString();
cbryant02
  • 583
  • 4
  • 16
  • See [this answer](https://stackoverflow.com/a/8708357/6288436) for a solution that doesn't redirect System.out. This is also the first result that comes up on Google, and I'm sure you got suggested that thread when you made this question. – cbryant02 May 12 '19 at 06:29
  • A. I didn't read that suggestion...thanks for the code, but it doesn't work... – user6441133 May 12 '19 at 07:06
  • Does it throw an exception or is the string just empty? The method printing the error might not be using `System.out`, try `System.setErr()`. – cbryant02 May 12 '19 at 07:37
  • The code fails compilation...I attached an image (Can't you see it?) – user6441133 May 12 '19 at 07:49
  • Ah, my bad. I forgot `setOut` doesn't use Writer classes. See my edit. It's basically a simplified version of the linked thread. – cbryant02 May 12 '19 at 08:22
  • Sorry, it compiles but returns an empty string now – user6441133 May 13 '19 at 07:47
  • Log4J probably uses some other output stream then. From what I can see it's more complicated than just capturing `System.out` or `System.err`. I don't use Log4J so I wouldn't know how to do this personally, but [here's](https://stackoverflow.com/questions/28043566/capture-log4j-output) the best help I can give you. – cbryant02 May 13 '19 at 15:48
  • I found out the solution...if any one wants to use... private java.io.ByteArrayOutputStream out; out = new java.io.ByteArrayOutputStream(); System.setOut(new java.io.PrintStream(out)); out.toString(); – user6441133 May 26 '19 at 07:07