2020-02-07 00:35:46 +03:00
|
|
|
package logger
|
|
|
|
|
2020-02-07 00:39:08 +03:00
|
|
|
import (
|
|
|
|
"context"
|
2020-02-21 10:57:59 +03:00
|
|
|
"io"
|
2020-11-04 00:38:12 +03:00
|
|
|
"os"
|
2020-02-07 00:39:08 +03:00
|
|
|
)
|
2020-02-07 00:35:46 +03:00
|
|
|
|
|
|
|
type Option func(*Options)
|
|
|
|
|
|
|
|
type Options struct {
|
2020-02-21 10:57:59 +03:00
|
|
|
// The logging level the logger should log at. default is `InfoLevel`
|
2020-02-20 11:26:12 +03:00
|
|
|
Level Level
|
2020-02-21 10:57:59 +03:00
|
|
|
// fields to always be logged
|
|
|
|
Fields map[string]interface{}
|
|
|
|
// It's common to set this to a file, or leave it default which is `os.Stderr`
|
|
|
|
Out io.Writer
|
2020-04-26 17:11:53 +03:00
|
|
|
// Caller skip frame count for file:line info
|
|
|
|
CallerSkipCount int
|
2020-02-21 10:57:59 +03:00
|
|
|
// Alternative options
|
2020-02-07 00:35:46 +03:00
|
|
|
Context context.Context
|
|
|
|
}
|
2020-02-20 11:26:12 +03:00
|
|
|
|
2020-10-16 09:38:57 +03:00
|
|
|
func NewOptions(opts ...Option) Options {
|
2020-11-04 00:38:12 +03:00
|
|
|
options := Options{
|
|
|
|
Level: InfoLevel,
|
|
|
|
Fields: make(map[string]interface{}),
|
|
|
|
Out: os.Stderr,
|
|
|
|
CallerSkipCount: 2,
|
|
|
|
Context: context.Background(),
|
|
|
|
}
|
2020-10-16 09:38:57 +03:00
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
|
|
|
return options
|
|
|
|
}
|
|
|
|
|
2020-02-21 10:57:59 +03:00
|
|
|
// WithFields set default fields for the logger
|
|
|
|
func WithFields(fields map[string]interface{}) Option {
|
|
|
|
return func(args *Options) {
|
|
|
|
args.Fields = fields
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithLevel set default level for the logger
|
|
|
|
func WithLevel(level Level) Option {
|
|
|
|
return func(args *Options) {
|
|
|
|
args.Level = level
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithOutput set default output writer for the logger
|
|
|
|
func WithOutput(out io.Writer) Option {
|
|
|
|
return func(args *Options) {
|
|
|
|
args.Out = out
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-26 17:11:53 +03:00
|
|
|
// WithCallerSkipCount set frame count to skip
|
|
|
|
func WithCallerSkipCount(c int) Option {
|
|
|
|
return func(args *Options) {
|
|
|
|
args.CallerSkipCount = c
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-21 10:57:59 +03:00
|
|
|
func SetOption(k, v interface{}) Option {
|
2020-02-20 11:26:12 +03:00
|
|
|
return func(o *Options) {
|
2020-02-21 10:57:59 +03:00
|
|
|
if o.Context == nil {
|
|
|
|
o.Context = context.Background()
|
|
|
|
}
|
|
|
|
o.Context = context.WithValue(o.Context, k, v)
|
2020-02-20 11:26:12 +03:00
|
|
|
}
|
|
|
|
}
|