micro/debug/log/os.go

82 lines
1.2 KiB
Go
Raw Normal View History

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