From f75c70db943650bcabad34c327415afd35428617 Mon Sep 17 00:00:00 2001 From: Mikhail Klementev Date: Thu, 6 Apr 2023 18:00:46 +0000 Subject: [PATCH] Log container stdout at trace level --- container.go | 37 ++++++++++++++++++++++++++++++------- main.go | 8 +++++--- 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/container.go b/container.go index 0a1df22..f9648a5 100644 --- a/container.go +++ b/container.go @@ -5,6 +5,7 @@ package main import ( + "bufio" "errors" "fmt" "os" @@ -64,6 +65,12 @@ func (c container) Build(imagePath string) (output string, err error) { } func (c container) Run(workdir string, command string) (output string, err error) { + flog := log.With(). + Str("container", c.name). + Str("workdir", workdir). + Str("command", command). + Logger() + var args []string args = append(args, "run", "--rm") args = append(args, c.Args...) @@ -78,23 +85,39 @@ func (c container) Run(workdir string, command string) (output string, err error log.Debug().Msgf("%v", cmd) + stdout, err := cmd.StdoutPipe() + if err != nil { + return + } + cmd.Stderr = cmd.Stdout + timer := time.AfterFunc(c.timeout, func() { - log.Info().Str("container", c.name). - Str("workdir", workdir). - Str("command", command). - Msg("killing container by timeout") + flog.Info().Msg("killing container by timeout") cmd.Process.Kill() }) defer timer.Stop() - raw, err := cmd.CombinedOutput() + err = cmd.Start() + if err != nil { + return + } + + go func() { + scanner := bufio.NewScanner(stdout) + for scanner.Scan() { + m := scanner.Text() + output += m + "\n" + flog.Trace().Str("stdout", m).Msg("") + } + }() + + err = cmd.Wait() if err != nil { e := fmt.Sprintf("error `%v` for cmd `%v` with output `%v`", - err, command, string(raw)) + err, command, output) err = errors.New(e) return } - output = string(raw) return } diff --git a/main.go b/main.go index 0d8f27b..50036a8 100644 --- a/main.go +++ b/main.go @@ -42,14 +42,14 @@ type CLI struct { Version VersionFlag `name:"version" help:"print version information and quit"` - LogLevel LogLevelFlag `enum:"debug,info,warn,error" default:"info"` + LogLevel LogLevelFlag `enum:"trace,debug,info,warn,error" default:"info"` } type LogLevelFlag string func (loglevel LogLevelFlag) AfterApply() error { switch loglevel { - case "debug": + case "debug", "trace": zerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string { short := file for i := len(file) - 1; i > 0; i-- { @@ -106,6 +106,8 @@ func main() { var loglevel zerolog.Level switch cli.LogLevel { + case "trace": + loglevel = zerolog.TraceLevel case "debug": loglevel = zerolog.DebugLevel case "info": @@ -132,7 +134,7 @@ func main() { &LevelWriter{Writer: &lumberjack.Logger{ Filename: usr.HomeDir + "/.out-of-tree/logs/out-of-tree.log", }, - Level: zerolog.DebugLevel, + Level: zerolog.TraceLevel, }, ))