jsonlog.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package jsonlog
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "time"
  6. )
  7. // JSONLog represents a log message, typically a single entry from a given log stream.
  8. // JSONLogs can be easily serialized to and from JSON and support custom formatting.
  9. type JSONLog struct {
  10. // Log is the log message
  11. Log string `json:"log,omitempty"`
  12. // Stream is the log source
  13. Stream string `json:"stream,omitempty"`
  14. // Created is the created timestamp of log
  15. Created time.Time `json:"time"`
  16. }
  17. // Format returns the log formatted according to format
  18. // If format is nil, returns the log message
  19. // If format is json, returns the log marshalled in json format
  20. // By defalut, returns the log with the log time formatted according to format.
  21. func (jl *JSONLog) Format(format string) (string, error) {
  22. if format == "" {
  23. return jl.Log, nil
  24. }
  25. if format == "json" {
  26. m, err := json.Marshal(jl)
  27. return string(m), err
  28. }
  29. return fmt.Sprintf("%s %s", jl.Created.Format(format), jl.Log), nil
  30. }
  31. // Reset resets the log to nil.
  32. func (jl *JSONLog) Reset() {
  33. jl.Log = ""
  34. jl.Stream = ""
  35. jl.Created = time.Time{}
  36. }