-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.go
67 lines (57 loc) · 2.01 KB
/
setup.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
// Copyright (C) 2021 Mya Pitzeruse
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package zaputil
import (
"context"
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// DefaultConfig returns the default configuration for zap to use. By default, it logs at an info level and infers the
// log format based on the stdout device. If it looks like a terminal session, then it uses the console format.
func DefaultConfig() Config {
format := "json"
if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 {
format = "console" // looks like terminal session, use console logging
}
return Config{
Level: "info",
Format: format,
}
}
// Config encapsulates the configurable elements of the logger.
type Config struct {
Level string `json:"level" usage:"adjust the verbosity of the logs" default:"info"`
Format string `json:"format" usage:"configure the format of the logs" default:"json"`
}
// Setup creates a logger given the provided configuration.
func Setup(ctx context.Context, cfg Config) context.Context {
level := zapcore.InfoLevel
if cfg.Level != "" {
err := (&level).Set(cfg.Level)
if err != nil {
panic(err)
}
}
zapConfig := zap.NewProductionConfig()
zapConfig.Level.SetLevel(level)
zapConfig.Encoding = cfg.Format
zapConfig.Sampling = nil // don't sample
logger, err := zapConfig.Build()
if err != nil {
panic(err)
}
return ToContext(ctx, logger)
}