Skip to content

Commit e8c5eed

Browse files
committed
Remove the logs.Log variable and replace it with logr.Logger in the remaining code
Signed-off-by: Richard Wall <[email protected]>
1 parent fd8d0de commit e8c5eed

File tree

4 files changed

+42
-28
lines changed

4 files changed

+42
-28
lines changed

pkg/datagatherer/k8s/cache.go

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
package k8s
22

33
import (
4+
"fmt"
45
"time"
56

7+
"github.com/go-logr/logr"
68
"github.com/pmylund/go-cache"
79
"k8s.io/apimachinery/pkg/types"
810

911
"github.com/jetstack/preflight/api"
10-
"github.com/jetstack/preflight/pkg/logs"
1112
)
1213

1314
// time interface, this is used to fetch the current time
@@ -30,9 +31,17 @@ type cacheResource interface {
3031
GetNamespace() string
3132
}
3233

34+
func logCacheUpdateFailure(log logr.Logger, obj interface{}, operation string) {
35+
// We use WithCallStackHelper to ensure the correct caller line numbers in the log messages
36+
helper, log := log.WithCallStackHelper()
37+
helper()
38+
err := fmt.Errorf("not a cacheResource type: %T missing metadata/uid field", obj)
39+
log.Error(err, "Cache update failure", "operation", operation)
40+
}
41+
3342
// onAdd handles the informer creation events, adding the created runtime.Object
3443
// to the data gatherer's cache. The cache key is the uid of the object
35-
func onAdd(obj interface{}, dgCache *cache.Cache) {
44+
func onAdd(log logr.Logger, obj interface{}, dgCache *cache.Cache) {
3645
item, ok := obj.(cacheResource)
3746
if ok {
3847
cacheObject := &api.GatheredResource{
@@ -41,36 +50,34 @@ func onAdd(obj interface{}, dgCache *cache.Cache) {
4150
dgCache.Set(string(item.GetUID()), cacheObject, cache.DefaultExpiration)
4251
return
4352
}
44-
logs.Log.Printf("could not %q resource to the cache, missing metadata/uid field", "add")
45-
53+
logCacheUpdateFailure(log, obj, "add")
4654
}
4755

4856
// onUpdate handles the informer update events, replacing the old object with the new one
4957
// if it's present in the data gatherer's cache, (if the object isn't present, it gets added).
5058
// The cache key is the uid of the object
51-
func onUpdate(old, new interface{}, dgCache *cache.Cache) {
59+
func onUpdate(log logr.Logger, old, new interface{}, dgCache *cache.Cache) {
5260
item, ok := old.(cacheResource)
5361
if ok {
5462
cacheObject := updateCacheGatheredResource(string(item.GetUID()), new, dgCache)
5563
dgCache.Set(string(item.GetUID()), cacheObject, cache.DefaultExpiration)
5664
return
5765
}
58-
59-
logs.Log.Printf("could not %q resource to the cache, missing metadata/uid field", "update")
66+
logCacheUpdateFailure(log, old, "update")
6067
}
6168

6269
// onDelete handles the informer deletion events, updating the object's properties with the deletion
6370
// time of the object (but not removing the object from the cache).
6471
// The cache key is the uid of the object
65-
func onDelete(obj interface{}, dgCache *cache.Cache) {
72+
func onDelete(log logr.Logger, obj interface{}, dgCache *cache.Cache) {
6673
item, ok := obj.(cacheResource)
6774
if ok {
6875
cacheObject := updateCacheGatheredResource(string(item.GetUID()), obj, dgCache)
6976
cacheObject.DeletedAt = api.Time{Time: clock.now()}
7077
dgCache.Set(string(item.GetUID()), cacheObject, cache.DefaultExpiration)
7178
return
7279
}
73-
logs.Log.Printf("could not %q resource to the cache, missing metadata/uid field", "delete")
80+
logCacheUpdateFailure(log, obj, "delete")
7481
}
7582

7683
// creates a new updated instance of a cache object, with the resource

pkg/datagatherer/k8s/cache_test.go

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ import (
66
"time"
77

88
"github.com/d4l3k/messagediff"
9+
"github.com/go-logr/logr"
910
"github.com/pmylund/go-cache"
1011
"k8s.io/apimachinery/pkg/runtime"
12+
"k8s.io/klog/v2/ktesting"
1113

1214
"github.com/jetstack/preflight/api"
1315
)
@@ -23,7 +25,7 @@ func TestOnAddCache(t *testing.T) {
2325
tcs := map[string]struct {
2426
inputObjects []runtime.Object
2527
eventObjects []runtime.Object
26-
eventFunc func(old, obj interface{}, dgCache *cache.Cache)
28+
eventFunc func(log logr.Logger, old, obj interface{}, dgCache *cache.Cache)
2729
expected []*api.GatheredResource
2830
}{
2931
"add all objects": {
@@ -50,7 +52,7 @@ func TestOnAddCache(t *testing.T) {
5052
getObject("v1", "Service", "testservice", "testns", false),
5153
getObject("foobar/v1", "NotFoo", "notfoo", "testns", false),
5254
},
53-
eventFunc: func(old, new interface{}, dgCache *cache.Cache) { onDelete(old, dgCache) },
55+
eventFunc: func(log logr.Logger, old, new interface{}, dgCache *cache.Cache) { onDelete(log, old, dgCache) },
5456
expected: []*api.GatheredResource{
5557
makeGatheredResource(
5658
getObject("foobar/v1", "Foo", "testfoo", "testns", false),
@@ -98,16 +100,17 @@ func TestOnAddCache(t *testing.T) {
98100

99101
for name, tc := range tcs {
100102
t.Run(name, func(t *testing.T) {
103+
log := ktesting.NewLogger(t, ktesting.NewConfig(ktesting.Verbosity(10)))
101104
dgCache := cache.New(5*time.Minute, 30*time.Second)
102105
// adding initial objetcs to the cache
103106
for _, obj := range tc.inputObjects {
104-
onAdd(obj, dgCache)
107+
onAdd(log, obj, dgCache)
105108
}
106109

107110
// Testing event founction on set of objects
108111
for _, obj := range tc.eventObjects {
109112
if tc.eventFunc != nil {
110-
tc.eventFunc(obj, obj, dgCache)
113+
tc.eventFunc(log, obj, obj, dgCache)
111114
}
112115
}
113116

@@ -136,3 +139,14 @@ func TestOnAddCache(t *testing.T) {
136139
})
137140
}
138141
}
142+
143+
// TestNoneCache demonstrates that the cache helpers do not crash if passed a
144+
// non-cachable object, but log an error with a reference to the object type.
145+
func TestNoneCache(t *testing.T) {
146+
log := ktesting.NewLogger(t, ktesting.NewConfig(ktesting.Verbosity(10)))
147+
148+
type notCachable struct{}
149+
onAdd(log, &notCachable{}, nil)
150+
onUpdate(log, &notCachable{}, nil, nil)
151+
onDelete(log, &notCachable{}, nil)
152+
}

pkg/datagatherer/k8s/dynamic.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ import (
2323
"k8s.io/client-go/kubernetes"
2424
"k8s.io/client-go/kubernetes/scheme"
2525
k8scache "k8s.io/client-go/tools/cache"
26+
"k8s.io/klog/v2"
2627

2728
"github.com/jetstack/preflight/api"
2829
"github.com/jetstack/preflight/pkg/datagatherer"
29-
"github.com/jetstack/preflight/pkg/logs"
3030
)
3131

3232
// ConfigDynamic contains the configuration for the data-gatherer.
@@ -161,6 +161,7 @@ func (c *ConfigDynamic) NewDataGatherer(ctx context.Context) (datagatherer.DataG
161161
}
162162

163163
func (c *ConfigDynamic) newDataGathererWithClient(ctx context.Context, cl dynamic.Interface, clientset kubernetes.Interface) (datagatherer.DataGatherer, error) {
164+
log := klog.FromContext(ctx)
164165
if err := c.validate(); err != nil {
165166
return nil, err
166167
}
@@ -216,13 +217,13 @@ func (c *ConfigDynamic) newDataGathererWithClient(ctx context.Context, cl dynami
216217

217218
registration, err := newDataGatherer.informer.AddEventHandler(k8scache.ResourceEventHandlerFuncs{
218219
AddFunc: func(obj interface{}) {
219-
onAdd(obj, dgCache)
220+
onAdd(log, obj, dgCache)
220221
},
221222
UpdateFunc: func(old, new interface{}) {
222-
onUpdate(old, new, dgCache)
223+
onUpdate(log, old, new, dgCache)
223224
},
224225
DeleteFunc: func(obj interface{}) {
225-
onDelete(obj, dgCache)
226+
onDelete(log, obj, dgCache)
226227
},
227228
})
228229
if err != nil {
@@ -264,16 +265,17 @@ type DataGathererDynamic struct {
264265
// Returns error if the data gatherer informer wasn't initialized, Run blocks
265266
// until the stopCh is closed.
266267
func (g *DataGathererDynamic) Run(stopCh <-chan struct{}) error {
268+
log := klog.FromContext(g.ctx)
267269
if g.informer == nil {
268270
return fmt.Errorf("informer was not initialized, impossible to start")
269271
}
270272

271273
// attach WatchErrorHandler, it needs to be set before starting an informer
272274
err := g.informer.SetWatchErrorHandler(func(r *k8scache.Reflector, err error) {
273275
if strings.Contains(fmt.Sprintf("%s", err), "the server could not find the requested resource") {
274-
logs.Log.Printf("server missing resource for datagatherer of %q ", g.groupVersionResource)
276+
log.Info("server missing resource for datagatherer", "groupVersionResource", g.groupVersionResource)
275277
} else {
276-
logs.Log.Printf("datagatherer informer for %q has failed and is backing off due to error: %s", g.groupVersionResource, err)
278+
log.Info("datagatherer informer has failed and is backing off", "groupVersionResource", g.groupVersionResource, "reason", err)
277279
}
278280
})
279281
if err != nil {

pkg/logs/logs.go

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,6 @@ import (
3434
// upon which this code was based.
3535

3636
var (
37-
// This is the Agent's logger. For now, it is still a *log.Logger, but we
38-
// mean to migrate everything to slog with the klog backend. We avoid using
39-
// log.Default because log.Default is already used by the VCert library, and
40-
// we need to keep the agent's logger from the VCert's logger to be able to
41-
// remove the `vCert: ` prefix from the VCert logs.
42-
Log *log.Logger
4337

4438
// All but the essential logging flags will be hidden to avoid overwhelming
4539
// the user. The hidden flags can still be used. For example if a user does
@@ -120,9 +114,6 @@ func Initialize() error {
120114
// the agent, which still uses log.Printf.
121115
slog := slog.Default()
122116

123-
Log = &log.Logger{}
124-
Log.SetOutput(LogToSlogWriter{Slog: slog, Source: "agent"})
125-
126117
// Let's make sure the VCert library, which is the only library we import to
127118
// be using the global log.Default, also uses the common slog logger.
128119
vcertLog := log.Default()

0 commit comments

Comments
 (0)