logger.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Package logger defines interfaces that logger drivers implement to
  2. // log messages.
  3. //
  4. // The other half of a logger driver is the implementation of the
  5. // factory, which holds the contextual instance information that
  6. // allows multiple loggers of the same type to perform different
  7. // actions, such as logging to different locations.
  8. package logger
  9. import (
  10. "errors"
  11. "sync"
  12. "time"
  13. "github.com/docker/docker/pkg/timeutils"
  14. )
  15. // ErrReadLogsNotSupported is returned when the logger does not support reading logs.
  16. var ErrReadLogsNotSupported = errors.New("configured logging reader does not support reading")
  17. const (
  18. // TimeFormat is the time format used for timestamps sent to log readers.
  19. TimeFormat = timeutils.RFC3339NanoFixed
  20. logWatcherBufferSize = 4096
  21. )
  22. // Message is datastructure that represents record from some container.
  23. type Message struct {
  24. ContainerID string
  25. Line []byte
  26. Source string
  27. Timestamp time.Time
  28. }
  29. // Logger is the interface for docker logging drivers.
  30. type Logger interface {
  31. Log(*Message) error
  32. Name() string
  33. Close() error
  34. }
  35. // ReadConfig is the configuration passed into ReadLogs.
  36. type ReadConfig struct {
  37. Since time.Time
  38. Tail int
  39. Follow bool
  40. }
  41. // LogReader is the interface for reading log messages for loggers that support reading.
  42. type LogReader interface {
  43. // Read logs from underlying logging backend
  44. ReadLogs(ReadConfig) *LogWatcher
  45. }
  46. // LogWatcher is used when consuming logs read from the LogReader interface.
  47. type LogWatcher struct {
  48. // For sending log messages to a reader.
  49. Msg chan *Message
  50. // For sending error messages that occur while while reading logs.
  51. Err chan error
  52. closeNotifier chan struct{}
  53. closeOnce sync.Once
  54. }
  55. // NewLogWatcher returns a new LogWatcher.
  56. func NewLogWatcher() *LogWatcher {
  57. return &LogWatcher{
  58. Msg: make(chan *Message, logWatcherBufferSize),
  59. Err: make(chan error, 1),
  60. closeNotifier: make(chan struct{}),
  61. }
  62. }
  63. // Close notifies the underlying log reader to stop.
  64. func (w *LogWatcher) Close() {
  65. // only close if not already closed
  66. select {
  67. case <-w.closeNotifier:
  68. default:
  69. close(w.closeNotifier)
  70. }
  71. }
  72. // WatchClose returns a channel receiver that receives notification
  73. // when the watcher has been closed. This should only be called from
  74. // one goroutine.
  75. func (w *LogWatcher) WatchClose() <-chan struct{} {
  76. return w.closeNotifier
  77. }