Debian Codegraph @

examples/usage_example.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
18
19 import (
20 "fmt"
21 "math/rand"
22 "time"
23
24 "github.com/go-logr/logr"
25 )
26
27 // This application demonstrates the usage of logger.
28 // It's a simple reconciliation loop that pretends to
29 // receive notifications about updates from a some API
30 // server, make some changes, and then submit updates of
31 // its own.
32
33 // This uses object-based logging. It's also possible
34 // (but a bit trickier) to use file-level "base" loggers.
35
36 var objectMap = map[string]Object{
37 "obj1": {
38 Name: "obj1",
39 Kind: "one",
40 Details: 33,
41 },
42 "obj2": {
43 Name: "obj2",
44 Kind: "two",
45 Details: "hi",
46 },
47 "obj3": {
48 Name: "obj3",
49 Kind: "one",
50 Details: 1,
51 },
52 }
53
54 // Object is an app construct that might want to be logged.
55 type Object struct {
56 Name string
57 Kind string
58 Details any
59 }
60
61 // Client is a simulated client in this example app.
62 type Client struct {
63 objects map[string]Object
64 log logr.Logger
65 }
66
67 // Get retrieves an object.
68 func (c *Client) Get(key string) (Object, error) {
69 c.log.V(1).Info("fetching object", "key", key)
70 obj, ok := c.objects[key]
71 if !ok {
72 return Object{}, fmt.Errorf("no object %s exists", key)
73 }
74 c.log.V(1).Info("pretending to deserialize object", "key", key, "json", "[insert real json here]")
75 return obj, nil
76 }
77
78 // Save stores an object.
79 func (c *Client) Save(obj Object) error {
80 c.log.V(1).Info("saving object", "key", obj.Name, "object", obj)
81 if rand.Intn(2) == 0 {
82 return fmt.Errorf("couldn't save to %s", obj.Name)
83 }
84 c.log.V(1).Info("pretending to post object", "key", obj.Name, "url", "https://fake.test")
85 return nil
86 }
87
88 // WatchNext waits for object updates.
89 func (c *Client) WatchNext() string {
90 time.Sleep(2 * time.Second)
91
92 keyInd := rand.Intn(len(c.objects))
93
94 currInd := 0
95 for key := range c.objects {
96 if currInd == keyInd {
97 return key
98 }
99 currInd++
100 }
101
102 c.log.Info("watch ended")
103 return ""
104 }
105
106 // Controller is the main point of this example.
107 type Controller struct {
108 log logr.Logger
109 expectedKind string
110 client *Client
111 }
112
113 // Run starts the example controller.
114 func (c *Controller) Run() {
115 c.log.Info("starting reconciliation")
116
117 for key := c.client.WatchNext(); key != ""; key = c.client.WatchNext() {
118 // we can make more specific loggers if we always want to attach a particular named value
119 log := c.log.WithValues("key", key)
120
121 // fetch our object
122 obj, err := c.client.Get(key)
123 if err != nil {
124 log.Error(err, "unable to reconcile object")
125 continue
126 }
127
128 // make sure it's as expected
129 if obj.Kind != c.expectedKind {
130 log.Error(nil, "got object that wasn't expected kind", "actual-kind", obj.Kind, "object", obj)
131 continue
132 }
133
134 // always log the object with log messages
135 log = log.WithValues("object", obj)
136 log.V(1).Info("reconciling object for key")
137
138 // Do some complicated updates updates
139 obj.Details = obj.Details.(int) * 2 //nolint:forcetypeassert
140
141 // actually save the updates
142 log.V(1).Info("updating object", "details", obj.Details)
143 if err := c.client.Save(obj); err != nil {
144 log.Error(err, "unable to reconcile object")
145 }
146 }
147
148 c.log.Info("stopping reconciliation")
149 }
150
151 // NewController allocates and initializes a Controller.
152 func NewController(log logr.Logger, objectKind string) *Controller {
153 ctrlLogger := log.WithName("controller").WithName(objectKind)
154 client := &Client{
155 log: ctrlLogger.WithName("client"),
156 objects: objectMap,
157 }
158 return &Controller{
159 log: ctrlLogger,
160 expectedKind: objectKind,
161 client: client,
162 }
163 }
164
165 func main() {
166 // use a fake implementation just for demonstration purposes
167 log := NewTabLogger()
168
169 // update objects with the "one" kind
170 ctrl := NewController(log, "one")
171
172 ctrl.Run()
173 }