github.com/schwarzm/garden-linux@v0.0.0-20150507151835-33bca2147c47/old/logging/runner.go (about)

     1  package logging
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"os/exec"
     7  	"syscall"
     8  	"time"
     9  
    10  	"github.com/cloudfoundry/gunk/command_runner"
    11  	"github.com/pivotal-golang/lager"
    12  )
    13  
    14  type Runner struct {
    15  	command_runner.CommandRunner
    16  
    17  	Logger lager.Logger
    18  }
    19  
    20  func (runner *Runner) Run(cmd *exec.Cmd) error {
    21  	stdout := new(bytes.Buffer)
    22  	stderr := new(bytes.Buffer)
    23  
    24  	if cmd.Stdout == nil {
    25  		cmd.Stdout = stdout
    26  	} else {
    27  		cmd.Stdout = io.MultiWriter(cmd.Stdout, stdout)
    28  	}
    29  
    30  	if cmd.Stderr == nil {
    31  		cmd.Stderr = stderr
    32  	} else {
    33  		cmd.Stderr = io.MultiWriter(cmd.Stderr, stderr)
    34  	}
    35  
    36  	rLog := runner.Logger.Session("command", lager.Data{
    37  		"argv": cmd.Args,
    38  	})
    39  
    40  	started := time.Now()
    41  
    42  	rLog.Debug("starting")
    43  
    44  	err := runner.CommandRunner.Run(cmd)
    45  
    46  	data := lager.Data{
    47  		"took": time.Since(started).String(),
    48  	}
    49  
    50  	state := cmd.ProcessState
    51  	if state != nil {
    52  		data["exit-status"] = state.Sys().(syscall.WaitStatus).ExitStatus()
    53  	}
    54  
    55  	if err != nil {
    56  		data["stdout"] = stdout.String()
    57  		data["stderr"] = stderr.String()
    58  
    59  		rLog.Error("failed", err, data)
    60  	} else {
    61  		rLog.Debug("succeeded", data)
    62  	}
    63  
    64  	return err
    65  }