k8s.io/kubernetes@v1.29.3/test/integration/logs/functional/json/output_test.go (about) 1 /* 2 Copyright 2021 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package json 18 19 import ( 20 "io" 21 "os" 22 "strings" 23 "testing" 24 25 "github.com/go-logr/logr" 26 "go.uber.org/zap/zapcore" 27 28 logsapi "k8s.io/component-base/logs/api/v1" 29 logsjson "k8s.io/component-base/logs/json" 30 "k8s.io/klog/v2" 31 "k8s.io/klog/v2/test" 32 ) 33 34 func init() { 35 // hack/make-rules/test-integration.sh expects that all unit tests 36 // support -v and -vmodule. 37 klog.InitFlags(nil) 38 } 39 40 // TestJsonOutput tests the JSON logger, directly and as backend for klog. 41 func TestJSONOutput(t *testing.T) { 42 test.InitKlog(t) 43 newLogger := func(out io.Writer, v int, vmodule string) logr.Logger { 44 logger, _ := logsjson.NewJSONLogger(logsapi.VerbosityLevel(v), logsjson.AddNopSync(out), nil, 45 &zapcore.EncoderConfig{ 46 MessageKey: "msg", 47 CallerKey: "caller", 48 NameKey: "logger", 49 EncodeDuration: zapcore.StringDurationEncoder, 50 EncodeCaller: zapcore.ShortCallerEncoder, 51 }) 52 return logger 53 } 54 55 // If Go modules are turned off (for example, as in "make test-integration"), 56 // references to klog like k8s.io/klog/v2.ObjectRef.MarshalLog become 57 // k8s.io/kubernetes/vendor/k8s.io/klog/v2.ObjectRef.MarshalLog. 58 injectVendor := func(mapping map[string]string) map[string]string { 59 if os.Getenv("GO111MODULE") != "off" { 60 return mapping 61 } 62 for key, value := range mapping { 63 mapping[key] = strings.ReplaceAll(value, "k8s.io/klog/v2", "k8s.io/kubernetes/vendor/k8s.io/klog/v2") 64 } 65 return mapping 66 } 67 68 t.Run("direct", func(t *testing.T) { 69 test.Output(t, test.OutputConfig{ 70 NewLogger: newLogger, 71 ExpectedOutputMapping: injectVendor(test.ZaprOutputMappingDirect()), 72 }) 73 }) 74 75 t.Run("klog-backend", func(t *testing.T) { 76 test.Output(t, test.OutputConfig{ 77 NewLogger: newLogger, 78 AsBackend: true, 79 ExpectedOutputMapping: injectVendor(test.ZaprOutputMappingIndirect()), 80 }) 81 }) 82 }