mirror of
https://github.com/go-micro/go-micro.git
synced 2024-12-24 10:07:04 +02:00
logger: add caller info to default implementation (#1575)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
parent
7253635cd3
commit
a22da39e1c
@ -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...),
|
||||
@ -134,10 +143,11 @@ func (n *defaultLogger) Options() Options {
|
||||
func NewLogger(opts ...Option) Logger {
|
||||
// Default options
|
||||
options := Options{
|
||||
Level: InfoLevel,
|
||||
Fields: make(map[string]interface{}),
|
||||
Out: os.Stderr,
|
||||
Context: context.Background(),
|
||||
Level: InfoLevel,
|
||||
Fields: make(map[string]interface{}),
|
||||
Out: os.Stderr,
|
||||
CallerSkipCount: 1,
|
||||
Context: context.Background(),
|
||||
}
|
||||
|
||||
l := &defaultLogger{opts: options}
|
||||
|
@ -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")
|
||||
}
|
||||
|
@ -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 {
|
||||
|
Loading…
Reference in New Issue
Block a user