-
Notifications
You must be signed in to change notification settings - Fork 0
/
zap.go
55 lines (45 loc) · 1.09 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
package zapfx
import (
"context"
"fmt"
"go.uber.org/config"
"go.uber.org/fx"
"go.uber.org/zap"
)
// NewZapParams defines the dependencies of the zapfx module.
type NewZapParams struct {
fx.In
Config config.Provider
Lifecycle fx.Lifecycle
}
// NewZapResult defines the objects that the zapfx module provides.
type NewZapResult struct {
fx.Out
Level zap.AtomicLevel
Logger *zap.Logger
}
// NewZap exports functionality similar to Module, but allows the caller to wrap
// or modify NewZapResult. Most users should use Module instead.
func NewZap(p NewZapParams) (NewZapResult, error) {
var (
c = zap.NewProductionConfig()
raw = p.Config.Get(ConfigurationKey)
)
if err := raw.Populate(&c); err != nil {
return NewZapResult{}, fmt.Errorf("failed to load logging config: %v", err)
}
logger, err := c.Build()
if err != nil {
return NewZapResult{}, fmt.Errorf("failed to create zap logger: %v", err)
}
p.Lifecycle.Append(fx.Hook{
OnStop: func(context.Context) error {
logger.Sync()
return nil
},
})
return NewZapResult{
Level: c.Level,
Logger: logger,
}, nil
}