github.com/johngossman/docker@v1.6.0-rc5/daemon/logger/jsonfilelog/jsonfilelog.go (about)

     1  package jsonfilelog
     2  
     3  import (
     4  	"bytes"
     5  	"os"
     6  	"sync"
     7  
     8  	"github.com/docker/docker/daemon/logger"
     9  	"github.com/docker/docker/pkg/jsonlog"
    10  )
    11  
    12  // JSONFileLogger is Logger implementation for default docker logging:
    13  // JSON objects to file
    14  type JSONFileLogger struct {
    15  	buf *bytes.Buffer
    16  	f   *os.File   // store for closing
    17  	mu  sync.Mutex // protects buffer
    18  }
    19  
    20  // New creates new JSONFileLogger which writes to filename
    21  func New(filename string) (logger.Logger, error) {
    22  	log, err := os.OpenFile(filename, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  	return &JSONFileLogger{
    27  		f:   log,
    28  		buf: bytes.NewBuffer(nil),
    29  	}, nil
    30  }
    31  
    32  // Log converts logger.Message to jsonlog.JSONLog and serializes it to file
    33  func (l *JSONFileLogger) Log(msg *logger.Message) error {
    34  	l.mu.Lock()
    35  	defer l.mu.Unlock()
    36  	err := (&jsonlog.JSONLog{Log: string(msg.Line) + "\n", Stream: msg.Source, Created: msg.Timestamp}).MarshalJSONBuf(l.buf)
    37  	if err != nil {
    38  		return err
    39  	}
    40  	l.buf.WriteByte('\n')
    41  	_, err = l.buf.WriteTo(l.f)
    42  	if err != nil {
    43  		// this buffer is screwed, replace it with another to avoid races
    44  		l.buf = bytes.NewBuffer(nil)
    45  		return err
    46  	}
    47  	return nil
    48  }
    49  
    50  // Close closes underlying file
    51  func (l *JSONFileLogger) Close() error {
    52  	return l.f.Close()
    53  }
    54  
    55  // Name returns name of this logger
    56  func (l *JSONFileLogger) Name() string {
    57  	return "JSONFile"
    58  }