Log commands we run with original caller

This commit is contained in:
Tim Hockin 2023-02-10 15:13:05 -08:00
parent 1253f82cd9
commit f5057b7fa8
No known key found for this signature in database
1 changed files with 10 additions and 3 deletions

View File

@ -36,6 +36,7 @@ type logintf interface {
Info(msg string, keysAndValues ...interface{})
Error(err error, msg string, keysAndValues ...interface{})
V(level int) logr.Logger
WithCallDepth(depth int) logr.Logger
}
// NewRunner returns a new CommandRunner
@ -45,13 +46,19 @@ func NewRunner(log logintf) *Runner {
// Run runs given command
func (r *Runner) Run(ctx context.Context, cwd string, env []string, command string, args ...string) (string, error) {
return r.RunWithStdin(ctx, cwd, env, "", command, args...)
// call depth = 2 to erase the runWithStdin frame and this one
return runWithStdin(ctx, r.log.WithCallDepth(2), cwd, env, "", command, args...)
}
// RunWithStdin runs given command with stardart input
func (r *Runner) RunWithStdin(ctx context.Context, cwd string, env []string, stdin, command string, args ...string) (string, error) {
// call depth = 2 to erase the runWithStdin frame and this one
return runWithStdin(ctx, r.log.WithCallDepth(2), cwd, env, stdin, command, args...)
}
func runWithStdin(ctx context.Context, log logintf, cwd string, env []string, stdin, command string, args ...string) (string, error) {
cmdStr := cmdForLog(command, args...)
r.log.V(5).Info("running command", "cwd", cwd, "cmd", cmdStr)
log.V(5).Info("running command", "cwd", cwd, "cmd", cmdStr)
cmd := exec.CommandContext(ctx, command, args...)
if cwd != "" {
@ -75,7 +82,7 @@ func (r *Runner) RunWithStdin(ctx context.Context, cwd string, env []string, std
if err != nil {
return "", fmt.Errorf("Run(%s): %w: { stdout: %q, stderr: %q }", cmdStr, err, stdout, stderr)
}
r.log.V(6).Info("command result", "stdout", stdout, "stderr", stderr)
log.V(6).Info("command result", "stdout", stdout, "stderr", stderr)
return stdout, nil
}