Skip to content

Commit eb9ed0c

Browse files
committed
Add debug log for to-be-applied k8s objects
Allows for easier debugging when applying of objects fails, e.g. because the k8s API server rejects them for unknown reasons. Wraps the object in a struct to allow for lazy evaluation as per https://pkg.go.dev/log/slog#hdr-Performance_considerations. Signed-off-by: nscuro <nscuro@protonmail.com>
1 parent 233bf40 commit eb9ed0c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

pkg/k8s/clientset.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@ package k8s
22

33
import (
44
"context"
5+
"encoding/base64"
6+
"fmt"
7+
"log/slog"
8+
"strings"
9+
10+
"k8s.io/cli-runtime/pkg/printers"
511

612
"github.com/go-errors/errors"
713
tektonv1beta1client "github.com/tektoncd/pipeline/pkg/client/clientset/versioned/typed/pipeline/v1beta1"
@@ -89,6 +95,8 @@ func (c clientSet) Apply(ctx context.Context, obj runtime.Object, namespace stri
8995
return errors.Errorf("%s/%s: could not convert runtime object into unstructured data: %w", namespace, name, err)
9096
}
9197

98+
slog.Debug("applying object", "namespace", namespace, "forceConflicts", forceConflicts, "object", lazyObjectLogValue{obj})
99+
92100
_, err = c.dynamicClient.
93101
Resource(gvr.Resource).
94102
Namespace(namespace).
@@ -113,3 +121,23 @@ func (c clientSet) Apply(ctx context.Context, obj runtime.Object, namespace stri
113121
func (c clientSet) RESTMapper() meta.RESTMapper {
114122
return c.restMapper
115123
}
124+
125+
type lazyObjectLogValue struct {
126+
obj runtime.Object
127+
}
128+
129+
// LogValue implements the slog.LogValuer interface.
130+
func (l lazyObjectLogValue) LogValue() slog.Value {
131+
sb := strings.Builder{}
132+
yamlPrinter := printers.YAMLPrinter{}
133+
134+
err := yamlPrinter.PrintObj(l.obj, &sb)
135+
if err != nil {
136+
return slog.StringValue(fmt.Sprintf("(failed to print object: %v)", err))
137+
}
138+
139+
// Base64-encode the YAML to maintain indentation etc.
140+
b64 := base64.StdEncoding.EncodeToString([]byte(sb.String()))
141+
142+
return slog.StringValue(b64)
143+
}

0 commit comments

Comments
 (0)