From 2bcfb8561343292efabd0224da7e9a8d3c7c6c04 Mon Sep 17 00:00:00 2001 From: Asim Aslam Date: Thu, 19 Dec 2019 12:20:33 +0000 Subject: [PATCH] Add log Format option --- debug/log/log.go | 5 +++++ debug/log/options.go | 8 ++++++++ debug/log/os.go | 16 +++++++++++++--- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/debug/log/log.go b/debug/log/log.go index a5958ad3..374023b1 100644 --- a/debug/log/log.go +++ b/debug/log/log.go @@ -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 diff --git a/debug/log/options.go b/debug/log/options.go index b17c2f43..63281857 100644 --- a/debug/log/options.go +++ b/debug/log/options.go @@ -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{ diff --git a/debug/log/os.go b/debug/log/os.go index fe0612a0..ed96668d 100644 --- a/debug/log/os.go +++ b/debug/log/os.go @@ -15,7 +15,8 @@ import ( // Should stream from OS type osLog struct { - once sync.Once + format FormatFunc + once sync.Once sync.RWMutex buffer *ring.Buffer @@ -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), }