Use mutex for logger

This commit is contained in:
Arthur Barr
2018-03-05 10:15:09 +00:00
parent 782fe367a5
commit 1e0ba3d897

View File

@@ -21,6 +21,7 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"sync"
"time" "time"
) )
@@ -32,6 +33,7 @@ const errorLevel string = "ERROR"
// A Logger is used to log messages to stdout // A Logger is used to log messages to stdout
type Logger struct { type Logger struct {
mutex sync.Mutex
writer io.Writer writer io.Writer
debug bool debug bool
json bool json bool
@@ -39,8 +41,10 @@ type Logger struct {
pid int pid int
} }
// NewLogger creates a new logger
func NewLogger(writer io.Writer, debug bool, json bool) *Logger { func NewLogger(writer io.Writer, debug bool, json bool) *Logger {
return &Logger{ return &Logger{
mutex: sync.Mutex{},
writer: writer, writer: writer,
debug: debug, debug: debug,
json: json, json: json,
@@ -72,6 +76,7 @@ func (l *Logger) log(level string, msg string) {
"ibm_processId": l.pid, "ibm_processId": l.pid,
} }
s, err := l.format(entry) s, err := l.format(entry)
l.mutex.Lock()
if err != nil { if err != nil {
// TODO: Fix this // TODO: Fix this
fmt.Println(err) fmt.Println(err)
@@ -81,6 +86,7 @@ func (l *Logger) log(level string, msg string) {
} else { } else {
fmt.Fprint(l.writer, s) fmt.Fprint(l.writer, s)
} }
l.mutex.Unlock()
} }
func (l *Logger) LogDirect(msg string) { func (l *Logger) LogDirect(msg string) {