jsonlog.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. // Attrs is the list of extra attributes provided by the user
  17. Attrs map[string]string `json:"attrs,omitempty"`
  18. }
  19. // Format returns the log formatted according to format
  20. // If format is nil, returns the log message
  21. // If format is json, returns the log marshaled in json format
  22. // By default, returns the log with the log time formatted according to format.
  23. func (jl *JSONLog) Format(format string) (string, error) {
  24. if format == "" {
  25. return jl.Log, nil
  26. }
  27. if format == "json" {
  28. m, err := json.Marshal(jl)
  29. return string(m), err
  30. }
  31. return fmt.Sprintf("%s %s", jl.Created.Format(format), jl.Log), nil
  32. }
  33. // Reset resets the log to nil.
  34. func (jl *JSONLog) Reset() {
  35. jl.Log = ""
  36. jl.Stream = ""
  37. jl.Created = time.Time{}
  38. }