2019-12-17 18:16:45 +00:00
|
|
|
package log
|
|
|
|
|
|
|
|
import (
|
2019-12-18 15:06:25 +00:00
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
2020-01-30 14:39:00 +03:00
|
|
|
"github.com/micro/go-micro/v2/util/ring"
|
2019-12-17 18:16:45 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Should stream from OS
|
2019-12-18 15:06:25 +00:00
|
|
|
type osLog struct {
|
2019-12-19 12:20:33 +00:00
|
|
|
format FormatFunc
|
|
|
|
once sync.Once
|
2019-12-18 18:36:42 +00:00
|
|
|
|
2019-12-18 15:06:25 +00:00
|
|
|
sync.RWMutex
|
2019-12-18 17:06:29 +00:00
|
|
|
buffer *ring.Buffer
|
|
|
|
subs map[string]*osStream
|
2019-12-18 15:06:25 +00:00
|
|
|
}
|
2019-12-17 18:16:45 +00:00
|
|
|
|
|
|
|
type osStream struct {
|
2019-12-18 15:06:25 +00:00
|
|
|
stream chan Record
|
2019-12-17 18:16:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Read reads log entries from the logger
|
|
|
|
func (o *osLog) Read(...ReadOption) ([]Record, error) {
|
2019-12-18 17:06:29 +00:00
|
|
|
var records []Record
|
|
|
|
|
|
|
|
// read the last 100 records
|
|
|
|
for _, v := range o.buffer.Get(100) {
|
|
|
|
records = append(records, v.Value.(Record))
|
|
|
|
}
|
|
|
|
|
|
|
|
return records, nil
|
2019-12-17 18:16:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Write writes records to log
|
|
|
|
func (o *osLog) Write(r Record) error {
|
2020-02-23 16:45:20 +03:00
|
|
|
o.buffer.Put(r)
|
|
|
|
return nil
|
2019-12-17 18:16:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Stream log records
|
|
|
|
func (o *osLog) Stream() (Stream, error) {
|
2019-12-18 15:06:25 +00:00
|
|
|
o.Lock()
|
|
|
|
defer o.Unlock()
|
2019-12-17 18:16:45 +00:00
|
|
|
|
2019-12-18 15:06:25 +00:00
|
|
|
// create stream
|
|
|
|
st := &osStream{
|
|
|
|
stream: make(chan Record, 128),
|
|
|
|
}
|
2019-12-17 18:16:45 +00:00
|
|
|
|
2019-12-18 15:06:25 +00:00
|
|
|
// save stream
|
|
|
|
o.subs[uuid.New().String()] = st
|
|
|
|
|
|
|
|
return st, nil
|
2019-12-17 18:16:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (o *osStream) Chan() <-chan Record {
|
|
|
|
return o.stream
|
|
|
|
}
|
|
|
|
|
|
|
|
func (o *osStream) Stop() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewLog(opts ...Option) Log {
|
2019-12-19 12:20:33 +00:00
|
|
|
options := Options{
|
|
|
|
Format: DefaultFormat,
|
|
|
|
}
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
|
|
|
|
2019-12-18 17:06:29 +00:00
|
|
|
l := &osLog{
|
2019-12-19 12:20:33 +00:00
|
|
|
format: options.Format,
|
2019-12-18 17:06:29 +00:00
|
|
|
buffer: ring.New(1024),
|
|
|
|
subs: make(map[string]*osStream),
|
2019-12-18 15:06:25 +00:00
|
|
|
}
|
2019-12-18 17:06:29 +00:00
|
|
|
|
|
|
|
return l
|
2019-12-17 18:16:45 +00:00
|
|
|
}
|