Permalink
Browse files

Fix to write fluent asynchronously

  • Loading branch information...
daichirata committed Dec 15, 2017
1 parent 884b834 commit 38301f437e598c84b097a7a4487d6fe927f56403
Showing with 47 additions and 9 deletions.
  1. +47 −9 logger.go
View
@@ -13,37 +13,48 @@ import (
)
var (
defaultAddress = "127.0.0.1:24224"
defaultAddress = "127.0.0.1:24224"
defaultFlushInterval = 5 * time.Second
)
type Config struct {
Address string
ConnectionTimeout time.Duration
FlushInterval time.Duration
}
func withDefaultConfig(c Config) Config {
if c.Address == "" {
c.Address = defaultAddress
}
if c.FlushInterval == 0 {
c.FlushInterval = defaultFlushInterval
}
return c
}
type Logger struct {
conf Config
conn io.WriteCloser
bmu sync.Mutex
cmu sync.Mutex
buf []byte
conf Config
conn io.WriteCloser
bmu sync.Mutex
cmu sync.Mutex
buf []byte
wg sync.WaitGroup
done chan struct{}
dirty chan struct{}
}
func NewLogger(c Config) (*Logger, error) {
logger := &Logger{
conf: withDefaultConfig(c),
buf: []byte{},
conf: withDefaultConfig(c),
buf: []byte{},
done: make(chan struct{}),
dirty: make(chan struct{}),
}
if err := logger.connect(); err != nil {
return nil, err
}
logger.start()
return logger, nil
}
@@ -69,10 +80,14 @@ func (logger *Logger) PostWithTime(tag string, t time.Time, obj interface{}) err
logger.buf = append(logger.buf, raw...)
logger.bmu.Unlock()
return logger.send()
go func() {
logger.dirty <- struct{}{}
}()
return nil
}
func (logger *Logger) Close() error {
logger.stop()
return logger.disconnect()
}
@@ -137,3 +152,26 @@ func (logger *Logger) send() error {
return err
}
func (logger *Logger) start() {
ticker := time.NewTicker(logger.conf.FlushInterval)
logger.wg.Add(1)
go func() {
defer logger.wg.Done()
for {
select {
case <-logger.done:
logger.send()
return
case <-logger.dirty:
case <-ticker.C:
}
logger.send()
}
}()
}
func (logger *Logger) stop() {
close(logger.done)
logger.wg.Wait()
}

0 comments on commit 38301f4

Please sign in to comment.