-
Notifications
You must be signed in to change notification settings - Fork 3
/
zap.go
75 lines (59 loc) · 1.38 KB
/
zap.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
package zap
import (
"context"
"github.com/alexfalkowski/go-service/env"
"go.uber.org/fx"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// LoggerParams for zap.
type LoggerParams struct {
fx.In
Lifecycle fx.Lifecycle
Config *Config
ZapConfig zap.Config
Environment env.Environment
Version env.Version
Name env.Name
}
// NewLogger using zap.
func NewLogger(params LoggerParams) (*zap.Logger, error) {
if !IsEnabled(params.Config) {
return zap.NewNop(), nil
}
fields := zap.Fields(
zap.String("name", string(params.Name)),
zap.String("environment", string(params.Environment)),
zap.String("version", string(params.Version)),
)
logger, err := params.ZapConfig.Build(fields)
if err != nil {
return nil, err
}
params.Lifecycle.Append(fx.Hook{
OnStop: func(_ context.Context) error {
_ = logger.Sync()
return nil
},
})
return logger, nil
}
// LogWithLogger for zap.
func LogWithLogger(msg string, err error, logger *zap.Logger, fields ...zapcore.Field) {
var fn LogFunc
if err != nil {
fn = logger.Error
} else {
fn = logger.Info
}
LogWithFunc(msg, err, fn, fields...)
}
// LogFunc for zap.
type LogFunc func(msg string, fields ...zapcore.Field)
// LogWithFunc for zap.
func LogWithFunc(msg string, err error, fn LogFunc, fields ...zapcore.Field) {
if err != nil {
fields = append(fields, zap.Error(err))
}
fn(msg, fields...)
}