jsonlog.go 852 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package jsonlog
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "time"
  8. )
  9. type JSONLog struct {
  10. Log string `json:"log,omitempty"`
  11. Stream string `json:"stream,omitempty"`
  12. Created time.Time `json:"time"`
  13. }
  14. func (jl *JSONLog) Format(format string) (string, error) {
  15. if format == "" {
  16. return jl.Log, nil
  17. }
  18. if format == "json" {
  19. m, err := json.Marshal(jl)
  20. return string(m), err
  21. }
  22. return fmt.Sprintf("[%s] %s", jl.Created.Format(format), jl.Log), nil
  23. }
  24. func WriteLog(src io.Reader, dst io.WriteCloser, format string) error {
  25. dec := json.NewDecoder(src)
  26. for {
  27. l := &JSONLog{}
  28. if err := dec.Decode(l); err == io.EOF {
  29. return nil
  30. } else if err != nil {
  31. log.Printf("Error streaming logs: %s", err)
  32. return err
  33. }
  34. line, err := l.Format(format)
  35. if err != nil {
  36. return err
  37. }
  38. fmt.Fprintf(dst, "%s", line)
  39. }
  40. }