blob: 313d914c10760e5b1775dc964220dd3939317b75 [file] [log] [blame]
Scott Baker2d897982019-09-24 11:50:08 -07001// Copyright 2019 The etcd Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package logutil
16
17import (
18 "sort"
19
20 "go.uber.org/zap"
21 "go.uber.org/zap/zapcore"
22)
23
24// DefaultZapLoggerConfig defines default zap logger configuration.
25var DefaultZapLoggerConfig = zap.Config{
26 Level: zap.NewAtomicLevelAt(zap.InfoLevel),
27
28 Development: false,
29 Sampling: &zap.SamplingConfig{
30 Initial: 100,
31 Thereafter: 100,
32 },
33
34 Encoding: "json",
35
36 // copied from "zap.NewProductionEncoderConfig" with some updates
37 EncoderConfig: zapcore.EncoderConfig{
38 TimeKey: "ts",
39 LevelKey: "level",
40 NameKey: "logger",
41 CallerKey: "caller",
42 MessageKey: "msg",
43 StacktraceKey: "stacktrace",
44 LineEnding: zapcore.DefaultLineEnding,
45 EncodeLevel: zapcore.LowercaseLevelEncoder,
46 EncodeTime: zapcore.ISO8601TimeEncoder,
47 EncodeDuration: zapcore.StringDurationEncoder,
48 EncodeCaller: zapcore.ShortCallerEncoder,
49 },
50
51 // Use "/dev/null" to discard all
52 OutputPaths: []string{"stderr"},
53 ErrorOutputPaths: []string{"stderr"},
54}
55
56// AddOutputPaths adds output paths to the existing output paths, resolving conflicts.
57func AddOutputPaths(cfg zap.Config, outputPaths, errorOutputPaths []string) zap.Config {
58 outputs := make(map[string]struct{})
59 for _, v := range cfg.OutputPaths {
60 outputs[v] = struct{}{}
61 }
62 for _, v := range outputPaths {
63 outputs[v] = struct{}{}
64 }
65 outputSlice := make([]string, 0)
66 if _, ok := outputs["/dev/null"]; ok {
67 // "/dev/null" to discard all
68 outputSlice = []string{"/dev/null"}
69 } else {
70 for k := range outputs {
71 outputSlice = append(outputSlice, k)
72 }
73 }
74 cfg.OutputPaths = outputSlice
75 sort.Strings(cfg.OutputPaths)
76
77 errOutputs := make(map[string]struct{})
78 for _, v := range cfg.ErrorOutputPaths {
79 errOutputs[v] = struct{}{}
80 }
81 for _, v := range errorOutputPaths {
82 errOutputs[v] = struct{}{}
83 }
84 errOutputSlice := make([]string, 0)
85 if _, ok := errOutputs["/dev/null"]; ok {
86 // "/dev/null" to discard all
87 errOutputSlice = []string{"/dev/null"}
88 } else {
89 for k := range errOutputs {
90 errOutputSlice = append(errOutputSlice, k)
91 }
92 }
93 cfg.ErrorOutputPaths = errOutputSlice
94 sort.Strings(cfg.ErrorOutputPaths)
95
96 return cfg
97}