diff --git a/broadcastwriter/broadcastwriter.go b/broadcastwriter/broadcastwriter.go index f094744..a16d8de 100644 --- a/broadcastwriter/broadcastwriter.go +++ b/broadcastwriter/broadcastwriter.go @@ -4,10 +4,11 @@ import ( "bytes" "encoding/json" "io" + "log" "sync" "time" - "github.com/docker/docker/utils" + "github.com/docker/docker/pkg/jsonlog" ) // BroadcastWriter accumulate multiple io.WriteCloser by stream. @@ -19,7 +20,7 @@ type BroadcastWriter struct { // AddWriter adds new io.WriteCloser for stream. // If stream is "", then all writes proceed as is. Otherwise every line from -// input will be packed to serialized utils.JSONLog. +// input will be packed to serialized jsonlog.JSONLog. func (w *BroadcastWriter) AddWriter(writer io.WriteCloser, stream string) { w.Lock() if _, ok := w.streams[stream]; !ok { @@ -53,9 +54,9 @@ func (w *BroadcastWriter) Write(p []byte) (n int, err error) { if stream == "" { continue } - b, err := json.Marshal(utils.JSONLog{Log: line, Stream: stream, Created: created}) + b, err := json.Marshal(jsonlog.JSONLog{Log: line, Stream: stream, Created: created}) if err != nil { - utils.Errorf("Error making JSON log line: %s", err) + log.Printf("Error making JSON log line: %s", err) continue } b = append(b, '\n') diff --git a/jsonlog/jsonlog.go b/jsonlog/jsonlog.go new file mode 100644 index 0000000..ecf4457 --- /dev/null +++ b/jsonlog/jsonlog.go @@ -0,0 +1,45 @@ +package jsonlog + +import ( + "encoding/json" + "fmt" + "io" + "log" + "time" +) + +type JSONLog struct { + Log string `json:"log,omitempty"` + Stream string `json:"stream,omitempty"` + Created time.Time `json:"time"` +} + +func (jl *JSONLog) Format(format string) (string, error) { + if format == "" { + return jl.Log, nil + } + if format == "json" { + m, err := json.Marshal(jl) + return string(m), err + } + return fmt.Sprintf("[%s] %s", jl.Created.Format(format), jl.Log), nil +} + +func WriteLog(src io.Reader, dst io.WriteCloser, format string) error { + dec := json.NewDecoder(src) + for { + l := &JSONLog{} + + if err := dec.Decode(l); err == io.EOF { + return nil + } else if err != nil { + log.Printf("Error streaming logs: %s", err) + return err + } + line, err := l.Format(format) + if err != nil { + return err + } + fmt.Fprintf(dst, "%s", line) + } +}