1 // Copyright 2022 Chaos Mesh 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 // 15 16 package log 17 18 import ( 19 "io" 20 21 "github.com/go-logr/logr" 22 "github.com/go-logr/zapr" 23 "go.uber.org/zap" 24 "go.uber.org/zap/zapcore" 25 ) 26 27 // NewDefaultZapLogger is the recommended way to create a new logger, you could call this function to initialize the root 28 // logger of your application, and provide it to your components, by fx or manually. 29 func NewDefaultZapLogger() (logr.Logger, error) { 30 // change the configuration in the future if needed. 31 zapLogger, err := zap.NewDevelopment() 32 if err != nil { 33 return logr.Discard(), err 34 } 35 logger := zapr.NewLogger(zapLogger) 36 return logger, nil 37 } 38 39 // NewZapLoggerWithWriter creates a new logger with io.writer 40 // The provided encoder presets NewDevelopmentEncoderConfig used by NewDevelopmentConfig do not enable function name logging. 41 // To enable function name, a non-empty value for config.EncoderConfig.FunctionKey. 42 func NewZapLoggerWithWriter(out io.Writer) logr.Logger { 43 bWriter := out 44 config := zap.NewDevelopmentConfig() 45 config.EncoderConfig.FunctionKey = "function" 46 core := zapcore.NewCore(zapcore.NewJSONEncoder(config.EncoderConfig), zapcore.AddSync(bWriter), config.Level) 47 zapLogger := zap.New(core) 48 logger := zapr.NewLogger(zapLogger) 49 return logger 50 } 51