github.com/grange74/docker@v1.6.0-rc3/pkg/jsonlog/jsonlog.go (about) 1 package jsonlog 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "time" 8 9 log "github.com/Sirupsen/logrus" 10 ) 11 12 type JSONLog struct { 13 Log string `json:"log,omitempty"` 14 Stream string `json:"stream,omitempty"` 15 Created time.Time `json:"time"` 16 } 17 18 func (jl *JSONLog) Format(format string) (string, error) { 19 if format == "" { 20 return jl.Log, nil 21 } 22 if format == "json" { 23 m, err := json.Marshal(jl) 24 return string(m), err 25 } 26 return fmt.Sprintf("%s %s", jl.Created.Format(format), jl.Log), nil 27 } 28 29 func (jl *JSONLog) Reset() { 30 jl.Log = "" 31 jl.Stream = "" 32 jl.Created = time.Time{} 33 } 34 35 func WriteLog(src io.Reader, dst io.Writer, format string) error { 36 dec := json.NewDecoder(src) 37 l := &JSONLog{} 38 for { 39 if err := dec.Decode(l); err == io.EOF { 40 return nil 41 } else if err != nil { 42 log.Printf("Error streaming logs: %s", err) 43 return err 44 } 45 line, err := l.Format(format) 46 if err != nil { 47 return err 48 } 49 if _, err := io.WriteString(dst, line); err != nil { 50 return err 51 } 52 l.Reset() 53 } 54 }