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