mirror of
https://github.com/moby/moby.git
synced 2022-11-09 12:21:53 -05:00
Protect jsonfilelog writes with mutex
Signed-off-by: Alexander Morozov <lk4d4@docker.com>
This commit is contained in:
parent
50bf3cbedc
commit
bd8661e8fa
1 changed files with 11 additions and 2 deletions
|
@ -3,6 +3,7 @@ package jsonfilelog
|
|||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/docker/docker/daemon/logger"
|
||||
"github.com/docker/docker/pkg/jsonlog"
|
||||
|
@ -13,6 +14,7 @@ import (
|
|||
type JSONFileLogger struct {
|
||||
buf *bytes.Buffer
|
||||
f *os.File // store for closing
|
||||
mu sync.Mutex // protects buffer
|
||||
}
|
||||
|
||||
// New creates new JSONFileLogger which writes to filename
|
||||
|
@ -29,13 +31,20 @@ func New(filename string) (logger.Logger, error) {
|
|||
|
||||
// Log converts logger.Message to jsonlog.JSONLog and serializes it to file
|
||||
func (l *JSONFileLogger) Log(msg *logger.Message) error {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
err := (&jsonlog.JSONLog{Log: string(msg.Line) + "\n", Stream: msg.Source, Created: msg.Timestamp}).MarshalJSONBuf(l.buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.buf.WriteByte('\n')
|
||||
_, err = l.buf.WriteTo(l.f)
|
||||
if err != nil {
|
||||
// this buffer is screwed, replace it with another to avoid races
|
||||
l.buf = bytes.NewBuffer(nil)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close closes underlying file
|
||||
|
|
Loading…
Reference in a new issue