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
// DefaultLog logger
DefaultLog = NewLog()
// Default formatter
DefaultFormat = func(r Record) string { return r.Message.(string) }
)
// Log is debug log interface for reading and writing logs
@ -37,3 +39,6 @@ type Stream interface {
Chan() <-chan Record
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
// Size is the size of ring buffer
Size int
// Format specifies the output format
Format FormatFunc
}
// 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
func DefaultOptions() Options {
return Options{

View File

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