Add log Format option

This commit is contained in:
Asim Aslam 2019-12-19 12:20:33 +00:00
parent d52a111735
commit 2bcfb85613
3 changed files with 26 additions and 3 deletions

View File

@ -10,6 +10,8 @@ var (
DefaultSize = 1024 DefaultSize = 1024
// DefaultLog logger // DefaultLog logger
DefaultLog = NewLog() DefaultLog = NewLog()
// Default formatter
DefaultFormat = func(r Record) string { return r.Message.(string) }
) )
// Log is debug log interface for reading and writing logs // Log is debug log interface for reading and writing logs
@ -37,3 +39,6 @@ type Stream interface {
Chan() <-chan Record Chan() <-chan Record
Stop() error Stop() error
} }
// Format is a function which formats the output
type FormatFunc func(Record) string

View File

@ -11,6 +11,8 @@ type Options struct {
Name string Name string
// Size is the size of ring buffer // Size is the size of ring buffer
Size int Size int
// Format specifies the output format
Format FormatFunc
} }
// Name of the log // Name of the log
@ -27,6 +29,12 @@ func Size(s int) Option {
} }
} }
func Format(f FormatFunc) Option {
return func(o *Options) {
o.Format = f
}
}
// DefaultOptions returns default options // DefaultOptions returns default options
func DefaultOptions() Options { func DefaultOptions() Options {
return Options{ return Options{

View File

@ -15,7 +15,8 @@ import (
// Should stream from OS // Should stream from OS
type osLog struct { type osLog struct {
once sync.Once format FormatFunc
once sync.Once
sync.RWMutex sync.RWMutex
buffer *ring.Buffer buffer *ring.Buffer
@ -140,8 +141,9 @@ func (o *osLog) Write(r Record) error {
go o.run() go o.run()
}) })
b, _ := json.Marshal(r) // generate output
_, err := os.Stderr.Write(append(b, byte('\n'))) out := o.format(r) + "\n"
_, err := os.Stderr.Write([]byte(out))
return err return err
} }
@ -181,7 +183,15 @@ func (o *osStream) Stop() error {
} }
func NewLog(opts ...Option) Log { func NewLog(opts ...Option) Log {
options := Options{
Format: DefaultFormat,
}
for _, o := range opts {
o(&options)
}
l := &osLog{ l := &osLog{
format: options.Format,
buffer: ring.New(1024), buffer: ring.New(1024),
subs: make(map[string]*osStream), subs: make(map[string]*osStream),
} }