-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.go
149 lines (132 loc) · 4.97 KB
/
options.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// Copyright © 2023 KubeCub & Xinwei Xiong(cubxxw). All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
package log
import (
"fmt"
"strings"
"github.com/kubecub/log/json"
"github.com/spf13/pflag"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
flagLevel = "log.level"
flagDisableCaller = "log.disable-caller"
flagDisableStacktrace = "log.disable-stacktrace"
flagFormat = "log.format"
flagEnableColor = "log.enable-color"
flagOutputPaths = "log.output-paths"
flagErrorOutputPaths = "log.error-output-paths"
flagDevelopment = "log.development"
flagName = "log.name"
consoleFormat = "console"
jsonFormat = "json"
)
// Options contains configuration items related to log.
type Options struct {
OutputPaths []string `json:"output-paths" mapstructure:"output-paths"`
ErrorOutputPaths []string `json:"error-output-paths" mapstructure:"error-output-paths"`
Level string `json:"level" mapstructure:"level"`
Format string `json:"format" mapstructure:"format"`
DisableCaller bool `json:"disable-caller" mapstructure:"disable-caller"`
DisableStacktrace bool `json:"disable-stacktrace" mapstructure:"disable-stacktrace"`
EnableColor bool `json:"enable-color" mapstructure:"enable-color"`
Development bool `json:"development" mapstructure:"development"`
Name string `json:"name" mapstructure:"name"`
}
// NewOptions creates an Options object with default parameters.
func NewOptions() *Options {
return &Options{
Level: zapcore.InfoLevel.String(),
DisableCaller: false,
DisableStacktrace: false,
Format: consoleFormat,
EnableColor: false,
Development: false,
OutputPaths: []string{"stdout"},
ErrorOutputPaths: []string{"stderr"},
}
}
// Validate validate the options fields.
func (o *Options) Validate() []error {
errs := []error{}
var zapLevel zapcore.Level
if err := zapLevel.UnmarshalText([]byte(o.Level)); err != nil {
errs = append(errs, err)
}
format := strings.ToLower(o.Format)
if format != consoleFormat && format != jsonFormat {
errs = append(errs, fmt.Errorf("not a valid log format: %q", o.Format))
}
return errs
}
// AddFlags adds flags for log to the specified FlagSet object.
func (o *Options) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&o.Level, flagLevel, o.Level, "Minimum log output `LEVEL`.")
fs.BoolVar(&o.DisableCaller, flagDisableCaller, o.DisableCaller, "Disable output of caller information in the log.")
fs.BoolVar(&o.DisableStacktrace, flagDisableStacktrace,
o.DisableStacktrace, "Disable the log to record a stack trace for all messages at or above panic level.")
fs.StringVar(&o.Format, flagFormat, o.Format, "Log output `FORMAT`, support plain or json format.")
fs.BoolVar(&o.EnableColor, flagEnableColor, o.EnableColor, "Enable output ansi colors in plain format logs.")
fs.StringSliceVar(&o.OutputPaths, flagOutputPaths, o.OutputPaths, "Output paths of log.")
fs.StringSliceVar(&o.ErrorOutputPaths, flagErrorOutputPaths, o.ErrorOutputPaths, "Error output paths of log.")
fs.BoolVar(
&o.Development,
flagDevelopment,
o.Development,
"Development puts the logger in development mode, which changes "+
"the behavior of DPanicLevel and takes stacktraces more liberally.",
)
fs.StringVar(&o.Name, flagName, o.Name, "The name of the logger.")
}
func (o *Options) String() string {
data, _ := json.Marshal(o)
return string(data)
}
// Build constructs a global zap logger from the Config and Options.
func (o *Options) Build() error {
var zapLevel zapcore.Level
if err := zapLevel.UnmarshalText([]byte(o.Level)); err != nil {
zapLevel = zapcore.InfoLevel
}
encodeLevel := zapcore.CapitalLevelEncoder
if o.Format == consoleFormat && o.EnableColor {
encodeLevel = zapcore.CapitalColorLevelEncoder
}
zc := &zap.Config{
Level: zap.NewAtomicLevelAt(zapLevel),
Development: o.Development,
DisableCaller: o.DisableCaller,
DisableStacktrace: o.DisableStacktrace,
Sampling: &zap.SamplingConfig{
Initial: 100,
Thereafter: 100,
},
Encoding: o.Format,
EncoderConfig: zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "level",
TimeKey: "timestamp",
NameKey: "logger",
CallerKey: "caller",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: encodeLevel,
EncodeTime: timeEncoder,
EncodeDuration: milliSecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
EncodeName: zapcore.FullNameEncoder,
},
OutputPaths: o.OutputPaths,
ErrorOutputPaths: o.ErrorOutputPaths,
}
logger, err := zc.Build(zap.AddStacktrace(zapcore.PanicLevel))
if err != nil {
return err
}
zap.RedirectStdLog(logger.Named(o.Name))
zap.ReplaceGlobals(logger)
return nil
}