github.com/uber/kraken@v0.1.4/utils/log/logger.go (about) 1 // Copyright (c) 2016-2019 Uber Technologies, Inc. 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 package log 15 16 import ( 17 "go.uber.org/zap" 18 "go.uber.org/zap/zapcore" 19 ) 20 21 // Config defines Logger configuration. 22 type Config struct { 23 Level zapcore.Level `yaml:"level"` 24 Disable bool `yaml:"disable"` 25 ServiceName string `yaml:"service_name"` 26 Path string `yaml:"path"` 27 Encoding string `yaml:"encoding"` 28 EncodeTime zapcore.TimeEncoder `yaml:"timeEncoder" json:"-"` 29 } 30 31 func (c Config) applyDefaults() Config { 32 if c.Path == "" { 33 c.Path = "stderr" 34 } 35 if c.Encoding == "" { 36 c.Encoding = "console" 37 } 38 return c 39 } 40 41 // New creates a logger that is not default. 42 func New(c Config, fields map[string]interface{}) (*zap.Logger, error) { 43 c = c.applyDefaults() 44 if c.Disable { 45 return zap.NewNop(), nil 46 } 47 if fields == nil { 48 fields = map[string]interface{}{} 49 } 50 if c.ServiceName != "" { 51 fields["service_name"] = c.ServiceName 52 } 53 54 return zap.Config{ 55 Level: zap.NewAtomicLevelAt(c.Level), 56 Sampling: &zap.SamplingConfig{ 57 Initial: 100, 58 Thereafter: 100, 59 }, 60 Encoding: c.Encoding, 61 EncoderConfig: zapcore.EncoderConfig{ 62 MessageKey: "message", 63 NameKey: "logger_name", 64 LevelKey: "level", 65 TimeKey: "ts", 66 CallerKey: "caller", 67 EncodeLevel: zapcore.CapitalLevelEncoder, 68 EncodeTime: c.EncodeTime, 69 EncodeDuration: zapcore.SecondsDurationEncoder, 70 EncodeCaller: zapcore.ShortCallerEncoder, 71 }, 72 DisableStacktrace: true, 73 OutputPaths: []string{c.Path}, 74 InitialFields: fields, 75 }.Build() 76 }