/
zapx.go
62 lines (55 loc) · 1.6 KB
/
zapx.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
package zapx
import (
"fmt"
"os"
"path/filepath"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// New creates a default zap logger based with basic defaults.
// If `logpath` is set, will use json encoder and write to the provided filepath.
// If `dev` is true, will use zap.DevelopmentConfig with colors enabled, though
// if logpath is set, the json encoder (without colors) will be enforced.
// If `dev` is false, will use zap.ProductionConfig.
func New(logpath string, dev bool, opts ...Option) (l *zap.Logger, err error) {
var config zap.Config
if dev {
// Log: DebugLevel
// Encoder: console
// Errors: stderr
// Sampling: no
// Stacktraces: WarningLevel
// Colors: capitals
config = zap.NewDevelopmentConfig()
if logpath == "" {
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
} else {
// Log: InfoLevel
// Encoder: json
// Errors: stderr
// Sampling: yes
// Stacktraces: ErrorLevel
config = zap.NewProductionConfig()
}
// set log output configuration if provided
if logpath != "" {
if err = os.MkdirAll(filepath.Dir(logpath), os.ModePerm); err != nil {
return nil, fmt.Errorf("failed to create directories for logpath '%s': %s",
logpath, err.Error())
}
config.OutputPaths = append(config.OutputPaths, logpath)
config.Encoding = "json"
}
// apply additional options
for _, apply := range opts {
if err := apply(&config); err != nil {
return nil, err
}
}
// instantiate logger
if l, err = config.Build(); err != nil {
return nil, fmt.Errorf("new logger: %s", err.Error())
}
return
}