1 // Copyright 2022 Google LLC 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 // Package logging adds common logging hooks for cnrm applications 16 package logging 17 18 import ( 19 "io" 20 "os" 21 22 "github.com/go-logr/logr" 23 "github.com/go-logr/zapr" 24 "go.uber.org/zap/zapcore" 25 klog "sigs.k8s.io/controller-runtime/pkg/log" 26 "sigs.k8s.io/controller-runtime/pkg/log/zap" 27 ) 28 29 var logger = klog.Log 30 31 // SetupLogger configures the controller-runtime/pkg/log Logger to the 32 // standard configuration across cnrm applications, writing to os.Stdout. 33 func SetupLogger() { 34 klog.SetLogger(BuildLogger(os.Stdout)) 35 } 36 37 // BuildLogger constructs a logr.Logger object that matches the standard 38 // configuration across cnrm applications, writing to the io.Writer passed. 39 func BuildLogger(output io.Writer) logr.Logger { 40 encoderCfg := zapcore.EncoderConfig{ 41 MessageKey: "msg", 42 LevelKey: "severity", 43 NameKey: "logger", 44 TimeKey: "timestamp", 45 EncodeLevel: zapcore.LowercaseLevelEncoder, 46 EncodeTime: zapcore.ISO8601TimeEncoder, 47 EncodeDuration: zapcore.StringDurationEncoder, 48 } 49 encoder := zapcore.NewJSONEncoder(encoderCfg) 50 return zapr.NewLogger(zap.NewRaw(zap.WriteTo(output), zap.Encoder(encoder))) 51 } 52 53 // Fatal is a utility function to replace log.Fatal, which doesn't exist 54 // for logr loggers. 55 func Fatal(err error, msg string) { 56 logger.Error(err, msg) 57 os.Exit(1) 58 } 59