mirror of
https://github.com/retailcrm/mg-transport-core.git
synced 2025-01-31 13:51:41 +03:00
goroutine-safe BufferLogger
This commit is contained in:
commit
27aee62487
@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/op/go-logging"
|
||||
|
||||
@ -29,6 +30,7 @@ type BufferedLogger interface {
|
||||
// BufferLogger is an implementation of the BufferedLogger.
|
||||
type BufferLogger struct {
|
||||
buf bytes.Buffer
|
||||
rw sync.RWMutex
|
||||
}
|
||||
|
||||
// NewBufferedLogger returns new BufferedLogger instance.
|
||||
@ -38,29 +40,41 @@ func NewBufferedLogger() BufferedLogger {
|
||||
|
||||
// Read bytes from the logger buffer. io.Reader implementation.
|
||||
func (l *BufferLogger) Read(p []byte) (n int, err error) {
|
||||
defer l.rw.RUnlock()
|
||||
l.rw.RLock()
|
||||
return l.buf.Read(p)
|
||||
}
|
||||
|
||||
// String contents of the logger buffer. fmt.Stringer implementation.
|
||||
func (l *BufferLogger) String() string {
|
||||
defer l.rw.RUnlock()
|
||||
l.rw.RLock()
|
||||
return l.buf.String()
|
||||
}
|
||||
|
||||
// Bytes is a shorthand for the underlying bytes.Buffer method. Returns byte slice with the buffer contents.
|
||||
func (l *BufferLogger) Bytes() []byte {
|
||||
defer l.rw.RUnlock()
|
||||
l.rw.RLock()
|
||||
return l.buf.Bytes()
|
||||
}
|
||||
|
||||
// Reset is a shorthand for the underlying bytes.Buffer method. It will reset buffer contents.
|
||||
func (l *BufferLogger) Reset() {
|
||||
defer l.rw.Unlock()
|
||||
l.rw.Lock()
|
||||
l.buf.Reset()
|
||||
}
|
||||
|
||||
func (l *BufferLogger) write(level logging.Level, args ...interface{}) {
|
||||
defer l.rw.Unlock()
|
||||
l.rw.Lock()
|
||||
l.buf.WriteString(fmt.Sprintln(append([]interface{}{level.String(), "=>"}, args...)...))
|
||||
}
|
||||
|
||||
func (l *BufferLogger) writef(level logging.Level, format string, args ...interface{}) {
|
||||
defer l.rw.Unlock()
|
||||
l.rw.Lock()
|
||||
l.buf.WriteString(fmt.Sprintf(level.String()+" => "+format, args...))
|
||||
}
|
||||
|
||||
|
@ -25,10 +25,6 @@ func (t *BufferLoggerTest) SetupTest() {
|
||||
t.logger.Reset()
|
||||
}
|
||||
|
||||
func (t *BufferLoggerTest) Log() string {
|
||||
return t.logger.String()
|
||||
}
|
||||
|
||||
func (t *BufferLoggerTest) Test_Read() {
|
||||
t.logger.Debug("test")
|
||||
|
||||
@ -41,3 +37,17 @@ func (t *BufferLoggerTest) Test_Bytes() {
|
||||
t.logger.Debug("test")
|
||||
t.Assert().Equal([]byte(logging.DEBUG.String()+" => test\n"), t.logger.Bytes())
|
||||
}
|
||||
|
||||
func (t *BufferLoggerTest) Test_String() {
|
||||
t.logger.Debug("test")
|
||||
t.Assert().Equal(logging.DEBUG.String()+" => test\n", t.logger.String())
|
||||
}
|
||||
|
||||
func (t *BufferLoggerTest) TestRace() {
|
||||
go func() {
|
||||
t.logger.Debug("test")
|
||||
}()
|
||||
go func() {
|
||||
t.logger.String()
|
||||
}()
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user