Debian Codegraph @

examples/tab_logger.go

raw
1 /*
2 Copyright 2019 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 main implements a simple example of a logr.LogSink that logs to
18 // stderr in a tabular format. It is not intended to be a production logger.
19 package main
20
21 import (
22 "fmt"
23 "os"
24 "text/tabwriter"
25
26 "github.com/go-logr/logr"
27 )
28
29 // tabLogSink is a sample logr.LogSink that logs to stderr.
30 // It's terribly inefficient, and is only a basic example.
31 type tabLogSink struct {
32 name string
33 keyValues map[string]any
34 writer *tabwriter.Writer
35 }
36
37 var _ logr.LogSink = &tabLogSink{}
38
39 // Note that Init usually takes a pointer so it can modify the receiver to save
40 // runtime info.
41 func (*tabLogSink) Init(_ logr.RuntimeInfo) {
42 }
43
44 func (tabLogSink) Enabled(_ int) bool {
45 return true
46 }
47
48 func (l tabLogSink) Info(_ int, msg string, kvs ...any) {
49 _, _ = fmt.Fprintf(l.writer, "%s\t%s\t", l.name, msg)
50 for k, v := range l.keyValues {
51 _, _ = fmt.Fprintf(l.writer, "%s: %+v ", k, v)
52 }
53 for i := 0; i < len(kvs); i += 2 {
54 _, _ = fmt.Fprintf(l.writer, "%s: %+v ", kvs[i], kvs[i+1])
55 }
56 _, _ = fmt.Fprintf(l.writer, "\n")
57 _ = l.writer.Flush()
58 }
59
60 func (l tabLogSink) Error(err error, msg string, kvs ...any) {
61 kvs = append(kvs, "error", err)
62 l.Info(0, msg, kvs...)
63 }
64
65 func (l tabLogSink) WithName(name string) logr.LogSink {
66 return &tabLogSink{
67 name: l.name + "." + name,
68 keyValues: l.keyValues,
69 writer: l.writer,
70 }
71 }
72
73 func (l tabLogSink) WithValues(kvs ...any) logr.LogSink {
74 newMap := make(map[string]any, len(l.keyValues)+len(kvs)/2)
75 for k, v := range l.keyValues {
76 newMap[k] = v
77 }
78 for i := 0; i < len(kvs); i += 2 {
79 k := kvs[i].(string) //nolint:forcetypeassert
80 v := kvs[i+1]
81 newMap[k] = v
82 }
83 return &tabLogSink{
84 name: l.name,
85 keyValues: newMap,
86 writer: l.writer,
87 }
88 }
89
90 // NewTabLogger is the main entry-point to this implementation. App developers
91 // call this somewhere near main() and thenceforth only deal with logr.Logger.
92 func NewTabLogger() logr.Logger {
93 sink := &tabLogSink{
94 writer: tabwriter.NewWriter(os.Stderr, 40, 8, 2, '\t', 0),
95 }
96 return logr.New(sink)
97 }