log.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Package log provides debug logging
  2. package log
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "time"
  7. )
  8. var (
  9. // DefaultSize Default buffer size if any
  10. DefaultSize = 256
  11. // DefaultFormat Default formatter
  12. DefaultFormat = TextFormat
  13. )
  14. // Log is debug log interface for reading and writing logs
  15. type Log interface {
  16. // Read reads log entries from the logger
  17. Read(...ReadOption) ([]Record, error)
  18. // Write writes records to log
  19. Write(Record) error
  20. // Stream log records
  21. Stream() (Stream, error)
  22. }
  23. // Record is log record entry
  24. type Record struct {
  25. // Timestamp of logged event
  26. Timestamp time.Time `json:"timestamp"`
  27. // Metadata to enrich log record
  28. Metadata map[string]string `json:"metadata"`
  29. // Value contains log entry
  30. Message interface{} `json:"message"`
  31. }
  32. // Stream returns a log stream
  33. type Stream interface {
  34. Chan() <-chan Record
  35. Stop() error
  36. }
  37. // FormatFunc is a function which formats the output
  38. type FormatFunc func(Record) string
  39. // TextFormat returns text format
  40. func TextFormat(r Record) string {
  41. t := r.Timestamp.Format("2006-01-02 15:04:05")
  42. return fmt.Sprintf("%s %v ", t, r.Message)
  43. }
  44. // JSONFormat is a json Format func
  45. func JSONFormat(r Record) string {
  46. b, _ := json.Marshal(r)
  47. return string(b) + " "
  48. }