/daemon/logger/jsonfilelog/jsonfilelog.go

https://github.com/dotcloud/docker · Go · 187 lines · 156 code · 18 blank · 13 comment · 43 complexity · 12cefa502742b80fa82e941eb0d30e2b MD5 · raw file

  1. // Package jsonfilelog provides the default Logger implementation for
  2. // Docker logging. This logger logs to files on the host server in the
  3. // JSON format.
  4. package jsonfilelog // import "github.com/docker/docker/daemon/logger/jsonfilelog"
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "strconv"
  10. "sync"
  11. "github.com/docker/docker/daemon/logger"
  12. "github.com/docker/docker/daemon/logger/jsonfilelog/jsonlog"
  13. "github.com/docker/docker/daemon/logger/loggerutils"
  14. units "github.com/docker/go-units"
  15. "github.com/pkg/errors"
  16. "github.com/sirupsen/logrus"
  17. )
  18. // Name is the name of the file that the jsonlogger logs to.
  19. const Name = "json-file"
  20. // JSONFileLogger is Logger implementation for default Docker logging.
  21. type JSONFileLogger struct {
  22. mu sync.Mutex
  23. closed bool
  24. writer *loggerutils.LogFile
  25. readers map[*logger.LogWatcher]struct{} // stores the active log followers
  26. tag string // tag values requested by the user to log
  27. }
  28. func init() {
  29. if err := logger.RegisterLogDriver(Name, New); err != nil {
  30. logrus.Fatal(err)
  31. }
  32. if err := logger.RegisterLogOptValidator(Name, ValidateLogOpt); err != nil {
  33. logrus.Fatal(err)
  34. }
  35. }
  36. // New creates new JSONFileLogger which writes to filename passed in
  37. // on given context.
  38. func New(info logger.Info) (logger.Logger, error) {
  39. var capval int64 = -1
  40. if capacity, ok := info.Config["max-size"]; ok {
  41. var err error
  42. capval, err = units.FromHumanSize(capacity)
  43. if err != nil {
  44. return nil, err
  45. }
  46. if capval <= 0 {
  47. return nil, fmt.Errorf("max-size must be a positive number")
  48. }
  49. }
  50. var maxFiles = 1
  51. if maxFileString, ok := info.Config["max-file"]; ok {
  52. var err error
  53. maxFiles, err = strconv.Atoi(maxFileString)
  54. if err != nil {
  55. return nil, err
  56. }
  57. if maxFiles < 1 {
  58. return nil, fmt.Errorf("max-file cannot be less than 1")
  59. }
  60. }
  61. var compress bool
  62. if compressString, ok := info.Config["compress"]; ok {
  63. var err error
  64. compress, err = strconv.ParseBool(compressString)
  65. if err != nil {
  66. return nil, err
  67. }
  68. if compress && (maxFiles == 1 || capval == -1) {
  69. return nil, fmt.Errorf("compress cannot be true when max-file is less than 2 or max-size is not set")
  70. }
  71. }
  72. attrs, err := info.ExtraAttributes(nil)
  73. if err != nil {
  74. return nil, err
  75. }
  76. // no default template. only use a tag if the user asked for it
  77. tag, err := loggerutils.ParseLogTag(info, "")
  78. if err != nil {
  79. return nil, err
  80. }
  81. if tag != "" {
  82. attrs["tag"] = tag
  83. }
  84. var extra []byte
  85. if len(attrs) > 0 {
  86. var err error
  87. extra, err = json.Marshal(attrs)
  88. if err != nil {
  89. return nil, err
  90. }
  91. }
  92. buf := bytes.NewBuffer(nil)
  93. marshalFunc := func(msg *logger.Message) ([]byte, error) {
  94. if err := marshalMessage(msg, extra, buf); err != nil {
  95. return nil, err
  96. }
  97. b := buf.Bytes()
  98. buf.Reset()
  99. return b, nil
  100. }
  101. writer, err := loggerutils.NewLogFile(info.LogPath, capval, maxFiles, compress, marshalFunc, decodeFunc, 0640, getTailReader)
  102. if err != nil {
  103. return nil, err
  104. }
  105. return &JSONFileLogger{
  106. writer: writer,
  107. readers: make(map[*logger.LogWatcher]struct{}),
  108. tag: tag,
  109. }, nil
  110. }
  111. // Log converts logger.Message to jsonlog.JSONLog and serializes it to file.
  112. func (l *JSONFileLogger) Log(msg *logger.Message) error {
  113. l.mu.Lock()
  114. err := l.writer.WriteLogEntry(msg)
  115. l.mu.Unlock()
  116. return err
  117. }
  118. func marshalMessage(msg *logger.Message, extra json.RawMessage, buf *bytes.Buffer) error {
  119. logLine := msg.Line
  120. if msg.PLogMetaData == nil || (msg.PLogMetaData != nil && msg.PLogMetaData.Last) {
  121. logLine = append(msg.Line, '\n')
  122. }
  123. err := (&jsonlog.JSONLogs{
  124. Log: logLine,
  125. Stream: msg.Source,
  126. Created: msg.Timestamp,
  127. RawAttrs: extra,
  128. }).MarshalJSONBuf(buf)
  129. if err != nil {
  130. return errors.Wrap(err, "error writing log message to buffer")
  131. }
  132. err = buf.WriteByte('\n')
  133. return errors.Wrap(err, "error finalizing log buffer")
  134. }
  135. // ValidateLogOpt looks for json specific log options max-file & max-size.
  136. func ValidateLogOpt(cfg map[string]string) error {
  137. for key := range cfg {
  138. switch key {
  139. case "max-file":
  140. case "max-size":
  141. case "compress":
  142. case "labels":
  143. case "labels-regex":
  144. case "env":
  145. case "env-regex":
  146. case "tag":
  147. default:
  148. return fmt.Errorf("unknown log opt '%s' for json-file log driver", key)
  149. }
  150. }
  151. return nil
  152. }
  153. // Close closes underlying file and signals all the readers
  154. // that the logs producer is gone.
  155. func (l *JSONFileLogger) Close() error {
  156. l.mu.Lock()
  157. l.closed = true
  158. err := l.writer.Close()
  159. for r := range l.readers {
  160. r.ProducerGone()
  161. delete(l.readers, r)
  162. }
  163. l.mu.Unlock()
  164. return err
  165. }
  166. // Name returns name of this logger.
  167. func (l *JSONFileLogger) Name() string {
  168. return Name
  169. }