logger: add caller info to default implementation (#1575)

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2020-04-26 17:11:53 +03:00 committed by GitHub
parent 7253635cd3
commit a22da39e1c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 4 deletions

View File

@ -4,6 +4,7 @@ import (
"context"
"fmt"
"os"
"runtime"
"sort"
"sync"
"time"
@ -64,6 +65,10 @@ func (l *defaultLogger) Log(level Level, v ...interface{}) {
fields["level"] = level.String()
if _, file, line, ok := runtime.Caller(l.opts.CallerSkipCount); ok {
fields["caller"] = fmt.Sprintf("%s:%d", file, line)
}
rec := dlog.Record{
Timestamp: time.Now(),
Message: fmt.Sprint(v...),
@ -101,6 +106,10 @@ func (l *defaultLogger) Logf(level Level, format string, v ...interface{}) {
fields["level"] = level.String()
if _, file, line, ok := runtime.Caller(l.opts.CallerSkipCount); ok {
fields["caller"] = fmt.Sprintf("%s:%d", file, line)
}
rec := dlog.Record{
Timestamp: time.Now(),
Message: fmt.Sprintf(format, v...),
@ -137,6 +146,7 @@ func NewLogger(opts ...Option) Logger {
Level: InfoLevel,
Fields: make(map[string]interface{}),
Out: os.Stderr,
CallerSkipCount: 1,
Context: context.Background(),
}

View File

@ -14,4 +14,5 @@ func TestLogger(t *testing.T) {
h2.Trace("trace_msg2")
h2.Warn("warn_msg2")
l.Fields(map[string]interface{}{"key3": "val4"}).Log(InfoLevel, "test_msg")
}

View File

@ -14,6 +14,8 @@ type Options struct {
Fields map[string]interface{}
// It's common to set this to a file, or leave it default which is `os.Stderr`
Out io.Writer
// Caller skip frame count for file:line info
CallerSkipCount int
// Alternative options
Context context.Context
}
@ -39,6 +41,13 @@ func WithOutput(out io.Writer) Option {
}
}
// WithCallerSkipCount set frame count to skip
func WithCallerSkipCount(c int) Option {
return func(args *Options) {
args.CallerSkipCount = c
}
}
func SetOption(k, v interface{}) Option {
return func(o *Options) {
if o.Context == nil {