7 changed files with 113 additions and 7 deletions
@ -0,0 +1,24 @@ |
|||||
|
package log_test |
||||
|
|
||||
|
import ( |
||||
|
"context" |
||||
|
|
||||
|
"gitoa.ru/go-4devs/log" |
||||
|
"gitoa.ru/go-4devs/log/level" |
||||
|
) |
||||
|
|
||||
|
func ExampleDebug() { |
||||
|
logger := log.With(log.New(log.WithStdout()), |
||||
|
log.WithSource(2), |
||||
|
log.WithLevel(log.KeyLevel, level.Debug), |
||||
|
log.WithExit(level.Alert), |
||||
|
log.WithPanic(level.Emergency), |
||||
|
) |
||||
|
|
||||
|
log.SetLogger(logger) |
||||
|
|
||||
|
ctx := context.Background() |
||||
|
log.Debug(ctx, "debug message") |
||||
|
// Output:
|
||||
|
// msg="debug message" source=global_example_test.go:21 level=debug
|
||||
|
} |
@ -0,0 +1,45 @@ |
|||||
|
package log |
||||
|
|
||||
|
import ( |
||||
|
"context" |
||||
|
"fmt" |
||||
|
"path/filepath" |
||||
|
"runtime" |
||||
|
|
||||
|
"gitoa.ru/go-4devs/log/entry" |
||||
|
"gitoa.ru/go-4devs/log/field" |
||||
|
) |
||||
|
|
||||
|
func WithSource(depth int) Middleware { |
||||
|
const offset = 3 |
||||
|
|
||||
|
return func(ctx context.Context, data *entry.Entry, handler Logger) (int, error) { |
||||
|
pc, file, line, has := runtime.Caller(depth + offset) |
||||
|
if !has { |
||||
|
return handler(ctx, data.AddAny(KeyLevel, field.NilValue())) |
||||
|
} |
||||
|
|
||||
|
fnc := runtime.FuncForPC(pc) |
||||
|
|
||||
|
return handler(ctx, data.AddAny(KeySource, Source{ |
||||
|
Func: filepath.Base(fnc.Name()), |
||||
|
File: filepath.Base(file), |
||||
|
Line: line, |
||||
|
})) |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Source describes the location of a line of source code.
|
||||
|
type Source struct { |
||||
|
Func string `json:"func"` |
||||
|
File string `json:"file"` |
||||
|
Line int `json:"line"` |
||||
|
} |
||||
|
|
||||
|
func (l Source) MarshalText() ([]byte, error) { |
||||
|
return []byte(fmt.Sprintf("%s:%d", l.File, l.Line)), nil |
||||
|
} |
||||
|
|
||||
|
func (l Source) MarshalJSON() ([]byte, error) { |
||||
|
return fmt.Appendf([]byte{}, `{"file":"%s","line":%d,"func":"%s"}`, l.File, l.Line, l.Func), nil |
||||
|
} |
@ -0,0 +1,25 @@ |
|||||
|
package log_test |
||||
|
|
||||
|
import ( |
||||
|
"context" |
||||
|
|
||||
|
"gitoa.ru/go-4devs/log" |
||||
|
) |
||||
|
|
||||
|
func ExampleWithSource() { |
||||
|
ctx := context.Background() |
||||
|
logger := log.New(log.WithStdout()).With(log.WithSource(1)) |
||||
|
|
||||
|
logger.Debug(ctx, "debug message") |
||||
|
// Output:
|
||||
|
// msg="debug message" source=source_example_test.go:13
|
||||
|
} |
||||
|
|
||||
|
func ExampleWithSource_json() { |
||||
|
ctx := context.Background() |
||||
|
logger := log.New(log.WithStdout(), log.WithJSONFormat()).With(log.WithSource(1)) |
||||
|
|
||||
|
logger.Debug(ctx, "debug message") |
||||
|
// Output:
|
||||
|
// {"msg":"debug message","source":{"file":"source_example_test.go","line":22,"func":"log_test.ExampleWithSource_json"}}
|
||||
|
} |
Loading…
Reference in new issue