micro/logger/options.go

91 lines
2.3 KiB
Go
Raw Permalink Normal View History

package logger
2020-02-07 00:39:08 +03:00
import (
"context"
"io"
"os"
"reflect"
"go.unistack.org/micro/v4/options"
rutil "go.unistack.org/micro/v4/util/reflect"
)
// Options holds logger options
type Options struct {
// Out holds the output writer
Out io.Writer
// Context holds exernal options
Context context.Context
// Attrs holds additional attributes
Attrs []interface{}
// Name holds the logger name
Name string
// The logging level the logger should log
Level Level
// CallerSkipCount number of frmaes to skip
CallerSkipCount int
// ContextAttrFuncs contains funcs that executed before log func on context
ContextAttrFuncs []ContextAttrFunc
}
// NewOptions creates new options struct
func NewOptions(opts ...options.Option) Options {
options := Options{
Level: DefaultLevel,
Attrs: make([]interface{}, 0, 6),
Out: os.Stderr,
CallerSkipCount: DefaultCallerSkipCount,
Context: context.Background(),
ContextAttrFuncs: DefaultContextAttrFuncs,
}
for _, o := range opts {
o(&options)
}
return options
}
// WithContextAttrFuncs appends default funcs for the context arrts filler
func WithContextAttrFuncs(attrs ...interface{}) options.Option {
return func(src interface{}) error {
v, err := options.Get(src, ".ContextAttrFuncs")
if err != nil {
return err
} else if rutil.IsZero(v) {
v = reflect.MakeSlice(reflect.TypeOf(v), 0, len(attrs)).Interface()
}
cv := reflect.ValueOf(v)
for _, l := range attrs {
cv = reflect.Append(cv, reflect.ValueOf(l))
}
return options.Set(src, cv.Interface(), ".ContextAttrFuncs")
}
}
// WithAttrs set default fields for the logger
func WithAttrs(attrs ...interface{}) options.Option {
return func(src interface{}) error {
return options.Set(src, attrs, ".Attrs")
}
}
// WithLevel set default level for the logger
func WithLevel(lvl Level) options.Option {
return func(src interface{}) error {
return options.Set(src, lvl, ".Level")
}
}
// WithOutput set default output writer for the logger
func WithOutput(out io.Writer) options.Option {
return func(src interface{}) error {
return options.Set(src, out, ".Out")
}
}
// WithCallerSkipCount set frame count to skip
func WithCallerSkipCount(c int) options.Option {
return func(src interface{}) error {
return options.Set(src, c, ".CallerSkipCount")
}
}