From 1d28d70fd6f29889e09ba0bc37a82b869b72417f Mon Sep 17 00:00:00 2001 From: Jacob McCann Date: Wed, 28 Jun 2017 14:20:03 -0500 Subject: [PATCH] pretty logging for drone exec --- drone/exec/exec.go | 6 +++-- drone/exec/line.go | 67 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 drone/exec/line.go diff --git a/drone/exec/exec.go b/drone/exec/exec.go index d6096804..a4439974 100644 --- a/drone/exec/exec.go +++ b/drone/exec/exec.go @@ -375,7 +375,6 @@ func exec(c *cli.Context) error { return pipeline.New(compiled, pipeline.WithContext(ctx), - pipeline.WithLogger(defaultLogger), pipeline.WithTracer(pipeline.DefaultTracer), pipeline.WithLogger(defaultLogger), pipeline.WithEngine(engine), @@ -451,6 +450,9 @@ var defaultLogger = pipeline.LogFunc(func(proc *backend.Step, rc multipart.Reade if err != nil { return err } - io.Copy(os.Stderr, part) + + logstream := NewLineWriter(proc.Alias) + io.Copy(logstream, part) + return nil }) diff --git a/drone/exec/line.go b/drone/exec/line.go new file mode 100644 index 00000000..88491f0c --- /dev/null +++ b/drone/exec/line.go @@ -0,0 +1,67 @@ +package exec + +import ( + "fmt" + "os" + "strings" + "time" +) + +// Identifies the type of line in the logs. +const ( + LineStdout int = iota + LineStderr + LineExitCode + LineMetadata + LineProgress +) + +// Line is a line of console output. +type Line struct { + Proc string `json:"proc,omitempty"` + Time int64 `json:"time,omitempty"` + Type int `json:"type,omitempty"` + Pos int `json:"pos,omityempty"` + Out string `json:"out,omitempty"` +} + +// LineWriter sends logs to the client. +type LineWriter struct { + name string + num int + now time.Time + rep *strings.Replacer + lines []*Line +} + +// NewLineWriter returns a new line reader. +func NewLineWriter(name string) *LineWriter { + w := new(LineWriter) + w.name = name + w.num = 0 + w.now = time.Now().UTC() + + return w +} + +func (w *LineWriter) Write(p []byte) (n int, err error) { + out := string(p) + if w.rep != nil { + out = w.rep.Replace(out) + } + + line := &Line{ + Out: out, + Proc: w.name, + Pos: w.num, + Time: int64(time.Since(w.now).Seconds()), + Type: LineStdout, + } + + fmt.Fprintf(os.Stderr, "[%s:L%d:%ds] %s", w.name, w.num, int64(time.Since(w.now).Seconds()), out) + + w.num++ + + w.lines = append(w.lines, line) + return len(p), nil +}