Created
November 8, 2021 14:17
-
-
Save pohly/307a4f366013daaf9b925cebd3a822d0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Copyright 2018 The Kubernetes Authors. | |
Licensed under the Apache License, Version 2.0 (the "License"); | |
you may not use this file except in compliance with the License. | |
You may obtain a copy of the License at | |
http://www.apache.org/licenses/LICENSE-2.0 | |
Unless required by applicable law or agreed to in writing, software | |
distributed under the License is distributed on an "AS IS" BASIS, | |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
See the License for the specific language governing permissions and | |
limitations under the License. | |
*/ | |
package debugger | |
import ( | |
"flag" | |
"fmt" | |
"os" | |
"github.com/go-logr/logr" | |
"k8s.io/api/core/v1" | |
"k8s.io/apimachinery/pkg/types" | |
"k8s.io/component-base/config" | |
"k8s.io/component-base/logs" | |
_ "k8s.io/component-base/logs/json/register" | |
"k8s.io/klog/v2" | |
) | |
type formatter struct { | |
*v1.Pod | |
} | |
func (f formatter) String() string { | |
return fmt.Sprintf("%s/%s", f.Namespace, f.Name) | |
} | |
func (f formatter) MarshalLog() interface{} { | |
return struct { | |
Namespace, Name string | |
}{ | |
Namespace: f.Namespace, | |
Name: f.Name, | |
} | |
} | |
var _ logr.Marshaler = formatter{} | |
func init() { | |
klog.InitFlags(nil) | |
} | |
func ExampleFormatter() { | |
pod := &v1.Pod{} | |
pod.UID = types.UID("some-uid") | |
pod.Namespace = "ns" | |
pod.Name = "pod-name" | |
// Print as JSON to stdout. | |
os.Stderr = os.Stdout | |
options := logs.Options{ | |
Config: config.LoggingConfiguration{ | |
Format: "json", | |
}, | |
} | |
if err := options.ValidateAndApply(); err != nil { | |
fmt.Printf("unexpected error: %v\n", err) | |
} | |
klog.InfoS("JSON output", "pod", formatter{pod}) | |
options.Config.Format = "text" | |
if err := options.ValidateAndApply(); err != nil { | |
fmt.Printf("unexpected error: %v\n", err) | |
} | |
flag.Set("skip_headers", "true") | |
flag.Set("alsologtostderr", "false") | |
flag.Set("logtostderr", "false") | |
klog.SetOutput(os.Stdout) | |
klog.InfoS("text output", "pod", formatter{pod}) | |
// Output: | |
// {"ts":1636380925129.9956,"caller":"debugger/formatter_test.go:70","msg":"JSON output","v":0,"pod":{"Namespace":"ns","Name":"pod-name"}} | |
// "text output" pod="ns/pod-name" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment