Changing Jenkins log output in realtime using Groovy

import hudson.model.*

class StreamGobbler implements Runnable {
  private final InputStream is;
  private final PrintStream os;
 
  StreamGobbler(InputStream is, PrintStream os) {
    this.is = is;
    this.os = os;
  }
 
  private void handleLine(String line)
  {
    // put your custom handling here.
    println line
  }
    
  public void run() 
  {
    try 
    {
      def line = ""
      int c;
      while ((c = is.read()) != -1)
      {
        line += (char)c
        if (c == '\n')
        {
          os.print(">>> ")
     	  os.print(line)
          handleLine(line)
          line = "";
        }
      }
    } 
    catch (IOException x) 
    {
      // Handle error
    }
  }
}

myCommand = "ping 127.0.0.1 -n 6"
println myCommand

def proc = myCommand.execute();

// Any error message?
Thread errorGobbler = new Thread(new StreamGobbler(proc.getErrorStream(), System.err));

// Any output?
Thread outputGobbler = new Thread(new StreamGobbler(proc.getInputStream(), System.out));

errorGobbler.start();
outputGobbler.start();

// Any error?
int exitVal = proc.waitFor();
errorGobbler.join();   // Handle condition where the
outputGobbler.join();  // process ends before the threads finish

Modification taken from https://wiki.sei.cmu.edu/confluence/display/java/FIO07-J.+Do+not+let+external+processes+block+on+IO+buffers


Schreibe einen Kommentar