Skip to content

Commit

Permalink
Add output of stderr in case of error to exec log message (#3862)
Browse files Browse the repository at this point in the history
If the command failed with a non-zero exit status there might be an error
message on stderr. Append the first line to the error message to ease the
search for its cause.
  • Loading branch information
hahnjo authored and danielnelson committed Mar 14, 2018
1 parent 6d66313 commit 8e51568
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions plugins/inputs/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ const sampleConfig = `
data_format = "influx"
`

const MaxStderrBytes = 512

type Exec struct {
Commands []string
Command string
Expand Down Expand Up @@ -96,15 +98,41 @@ func (c CommandRunner) Run(

cmd := exec.Command(split_cmd[0], split_cmd[1:]...)

var out bytes.Buffer
var (
out bytes.Buffer
stderr bytes.Buffer
)
cmd.Stdout = &out
cmd.Stderr = &stderr

if err := internal.RunTimeout(cmd, e.Timeout.Duration); err != nil {
switch e.parser.(type) {
case *nagios.NagiosParser:
AddNagiosState(err, acc)
default:
return nil, fmt.Errorf("exec: %s for command '%s'", err, command)
var errMessage = ""
if stderr.Len() > 0 {
stderr = removeCarriageReturns(stderr)
// Limit the number of bytes.
didTruncate := false
if stderr.Len() > MaxStderrBytes {
stderr.Truncate(MaxStderrBytes)
didTruncate = true
}
if i := bytes.IndexByte(stderr.Bytes(), '\n'); i > 0 {
// Only show truncation if the newline wasn't the last character.
if i < stderr.Len()-1 {
didTruncate = true
}
stderr.Truncate(i)
}
if didTruncate {
stderr.WriteString("...")
}

errMessage = fmt.Sprintf(": %s", stderr.String())
}
return nil, fmt.Errorf("exec: %s for command '%s'%s", err, command, errMessage)
}
} else {
switch e.parser.(type) {
Expand Down

0 comments on commit 8e51568

Please sign in to comment.