Debian Codegraph @

example_marshaler_test.go

raw
1 /*
2 Copyright 2021 The logr 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 logr_test
18
19 import (
20 "github.com/go-logr/logr"
21 )
22
23 // ObjectRef references a Kubernetes object
24 type ObjectRef struct {
25 Name string `json:"name"`
26 Namespace string `json:"namespace,omitempty"`
27 }
28
29 func (ref ObjectRef) String() string {
30 if ref.Namespace != "" {
31 return ref.Namespace + "/" + ref.Name
32 }
33 return ref.Name
34 }
35
36 func (ref ObjectRef) MarshalLog() any {
37 // We implement fmt.Stringer for non-structured logging, but we want the
38 // raw struct when using structured logs. Some logr implementations call
39 // String if it is present, so we want to convert this struct to something
40 // that doesn't have that method.
41 type forLog ObjectRef // methods do not survive type definitions
42 return forLog(ref)
43 }
44
45 var _ logr.Marshaler = ObjectRef{}
46
47 func ExampleMarshaler() {
48 l := NewStdoutLogger()
49 pod := ObjectRef{Namespace: "kube-system", Name: "some-pod"}
50 l.Info("as string", "pod", pod.String())
51 l.Info("as struct", "pod", pod)
52 // Output:
53 // "level"=0 "msg"="as string" "pod"="kube-system/some-pod"
54 // "level"=0 "msg"="as struct" "pod"={"name"="some-pod" "namespace"="kube-system"}
55 }