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" "context"
"fmt" "fmt"
"os" "os"
"runtime"
"sort" "sort"
"sync" "sync"
"time" "time"
@ -64,6 +65,10 @@ func (l *defaultLogger) Log(level Level, v ...interface{}) {
fields["level"] = level.String() 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{ rec := dlog.Record{
Timestamp: time.Now(), Timestamp: time.Now(),
Message: fmt.Sprint(v...), Message: fmt.Sprint(v...),
@ -101,6 +106,10 @@ func (l *defaultLogger) Logf(level Level, format string, v ...interface{}) {
fields["level"] = level.String() 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{ rec := dlog.Record{
Timestamp: time.Now(), Timestamp: time.Now(),
Message: fmt.Sprintf(format, v...), Message: fmt.Sprintf(format, v...),
@ -134,10 +143,11 @@ func (n *defaultLogger) Options() Options {
func NewLogger(opts ...Option) Logger { func NewLogger(opts ...Option) Logger {
// Default options // Default options
options := Options{ options := Options{
Level: InfoLevel, Level: InfoLevel,
Fields: make(map[string]interface{}), Fields: make(map[string]interface{}),
Out: os.Stderr, Out: os.Stderr,
Context: context.Background(), CallerSkipCount: 1,
Context: context.Background(),
} }
l := &defaultLogger{opts: options} l := &defaultLogger{opts: options}

View File

@ -14,4 +14,5 @@ func TestLogger(t *testing.T) {
h2.Trace("trace_msg2") h2.Trace("trace_msg2")
h2.Warn("warn_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{} Fields map[string]interface{}
// It's common to set this to a file, or leave it default which is `os.Stderr` // It's common to set this to a file, or leave it default which is `os.Stderr`
Out io.Writer Out io.Writer
// Caller skip frame count for file:line info
CallerSkipCount int
// Alternative options // Alternative options
Context context.Context 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 { func SetOption(k, v interface{}) Option {
return func(o *Options) { return func(o *Options) {
if o.Context == nil { if o.Context == nil {