2014-07-30 11:39:03 -04:00
|
|
|
package jsonlog
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"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
|
|
|
|
}
|
2015-01-28 17:33:15 -05:00
|
|
|
return fmt.Sprintf("%s %s", jl.Created.Format(format), jl.Log), nil
|
2014-07-30 11:39:03 -04:00
|
|
|
}
|
|
|
|
|
2014-09-18 11:04:18 -04:00
|
|
|
func (jl *JSONLog) Reset() {
|
|
|
|
jl.Log = ""
|
|
|
|
jl.Stream = ""
|
|
|
|
jl.Created = time.Time{}
|
|
|
|
}
|
|
|
|
|
2015-04-14 00:36:12 -04:00
|
|
|
func WriteLog(src io.Reader, dst io.Writer, format string, since time.Time) error {
|
2014-07-30 11:39:03 -04:00
|
|
|
dec := json.NewDecoder(src)
|
2014-09-18 11:04:18 -04:00
|
|
|
l := &JSONLog{}
|
2014-07-30 11:39:03 -04:00
|
|
|
for {
|
2015-04-14 00:36:12 -04:00
|
|
|
l.Reset()
|
2015-05-06 21:09:27 -04:00
|
|
|
if err := dec.Decode(l); err != nil {
|
|
|
|
if err == io.EOF {
|
|
|
|
return nil
|
|
|
|
}
|
2014-07-30 11:39:03 -04:00
|
|
|
return err
|
|
|
|
}
|
2015-04-14 00:36:12 -04:00
|
|
|
if !since.IsZero() && l.Created.Before(since) {
|
|
|
|
continue
|
|
|
|
}
|
2015-05-06 21:09:27 -04:00
|
|
|
|
2014-07-30 11:39:03 -04:00
|
|
|
line, err := l.Format(format)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2014-09-22 02:55:46 -04:00
|
|
|
if _, err := io.WriteString(dst, line); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2014-07-30 11:39:03 -04:00
|
|
|
}
|
|
|
|
}
|