Skip to content

Commit 14e04a5

Browse files
committed
pkg/ansible/*: use pkg/sdk/log instead of std log/logrus
test/ansible-operator/*: use logrus instead of std log
1 parent 1912537 commit 14e04a5

File tree

11 files changed

+118
-106
lines changed

11 files changed

+118
-106
lines changed

pkg/ansible/controller/controller.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,13 @@ package controller
1616

1717
import (
1818
"fmt"
19-
"log"
2019
"strings"
2120
"time"
2221

2322
"github.com/operator-framework/operator-sdk/pkg/ansible/events"
2423
"github.com/operator-framework/operator-sdk/pkg/ansible/runner"
24+
"github.com/operator-framework/operator-sdk/pkg/sdk/log"
2525

26-
"github.com/sirupsen/logrus"
2726
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2827
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2928
"k8s.io/apimachinery/pkg/runtime/schema"
@@ -44,7 +43,7 @@ type Options struct {
4443

4544
// Add - Creates a new ansible operator controller and adds it to the manager
4645
func Add(mgr manager.Manager, options Options) {
47-
logrus.Infof("Watching %s/%v, %s", options.GVK.Group, options.GVK.Version, options.GVK.Kind)
46+
log.Info("Watching resource", "Options.Group", options.GVK.Group, "Options.Version", options.GVK.Version, "Options.Kind", options.GVK.Kind)
4847
if options.EventHandlers == nil {
4948
options.EventHandlers = []events.EventHandler{}
5049
}
@@ -73,11 +72,11 @@ func Add(mgr manager.Manager, options Options) {
7372
Reconciler: aor,
7473
})
7574
if err != nil {
76-
log.Fatal(err)
75+
log.Fatal(err, "")
7776
}
7877
u := &unstructured.Unstructured{}
7978
u.SetGroupVersionKind(options.GVK)
8079
if err := c.Watch(&source.Kind{Type: u}, &crthandler.EnqueueRequestForObject{}); err != nil {
81-
log.Fatal(err)
80+
log.Fatal(err, "")
8281
}
8382
}

pkg/ansible/controller/reconcile.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ import (
2727
"github.com/operator-framework/operator-sdk/pkg/ansible/proxy/kubeconfig"
2828
"github.com/operator-framework/operator-sdk/pkg/ansible/runner"
2929
"github.com/operator-framework/operator-sdk/pkg/ansible/runner/eventapi"
30+
"github.com/operator-framework/operator-sdk/pkg/sdk/log"
3031

31-
"github.com/sirupsen/logrus"
3232
"k8s.io/api/core/v1"
3333
apierrors "k8s.io/apimachinery/pkg/api/errors"
3434
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -79,7 +79,7 @@ func (r *AnsibleOperatorReconciler) Reconcile(request reconcile.Request) (reconc
7979
pendingFinalizers := u.GetFinalizers()
8080
// If the resource is being deleted we don't want to add the finalizer again
8181
if finalizerExists && !deleted && !contains(pendingFinalizers, finalizer) {
82-
logrus.Debugf("Adding finalizer %s to resource", finalizer)
82+
log.V(2).Info("Adding finalizer to resource", "Finalizer", finalizer)
8383
finalizers := append(pendingFinalizers, finalizer)
8484
u.SetFinalizers(finalizers)
8585
err := r.Client.Update(context.TODO(), u)
@@ -88,14 +88,14 @@ func (r *AnsibleOperatorReconciler) Reconcile(request reconcile.Request) (reconc
8888
}
8989
}
9090
if !contains(pendingFinalizers, finalizer) && deleted {
91-
logrus.Info("Resource is terminated, skipping reconcilation")
91+
log.Info("Resource is terminated, skipping reconcilation")
9292
return reconcileResult, nil
9393
}
9494

9595
spec := u.Object["spec"]
9696
_, ok := spec.(map[string]interface{})
9797
if !ok {
98-
logrus.Debugf("spec was not found")
98+
log.V(log.VDebug).Info("spec was not found")
9999
u.Object["spec"] = map[string]interface{}{}
100100
err = r.Client.Update(context.TODO(), u)
101101
if err != nil {
@@ -170,7 +170,7 @@ func (r *AnsibleOperatorReconciler) Reconcile(request reconcile.Request) (reconc
170170
}
171171
if statusEvent.Event == "" {
172172
err := errors.New("did not receive playbook_on_stats event")
173-
logrus.Error(err.Error())
173+
log.Error(err, "")
174174
return reconcileResult, err
175175
}
176176

pkg/ansible/controller/status/types.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ import (
1818
"time"
1919

2020
"github.com/operator-framework/operator-sdk/pkg/ansible/runner/eventapi"
21-
"github.com/sirupsen/logrus"
21+
"github.com/operator-framework/operator-sdk/pkg/sdk/log"
22+
2223
"k8s.io/api/core/v1"
2324
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2425
)
@@ -128,7 +129,7 @@ func createConditionFromMap(cm map[string]interface{}) Condition {
128129
if ok {
129130
t, err := time.Parse("2006-01-02T15:04:05Z", ltts)
130131
if err != nil {
131-
logrus.Warningf("unable to parse time for status condition: %v", ltts)
132+
log.V(log.VWarn).Info("unable to parse time for status condition", "Time", ltts)
132133
} else {
133134
ltt = metav1.NewTime(t)
134135
}
@@ -158,7 +159,7 @@ func CreateFromMap(statusMap map[string]interface{}) Status {
158159
for _, ci := range conditionsInterface {
159160
cm, ok := ci.(map[string]interface{})
160161
if !ok {
161-
logrus.Warningf("unknown condition, removing condition: %v", ci)
162+
log.V(log.VWarn).Info("unknown condition, removing condition", "ConditionInterface", ci)
162163
continue
163164
}
164165
conditions = append(conditions, createConditionFromMap(cm))

pkg/ansible/events/log_events.go

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,11 @@
1515
package events
1616

1717
import (
18+
"errors"
19+
1820
"github.com/operator-framework/operator-sdk/pkg/ansible/runner/eventapi"
19-
"github.com/sirupsen/logrus"
21+
"github.com/operator-framework/operator-sdk/pkg/sdk/log"
22+
2023
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2124
)
2225

@@ -44,39 +47,44 @@ type loggingEventHandler struct {
4447
}
4548

4649
func (l loggingEventHandler) Handle(u *unstructured.Unstructured, e eventapi.JobEvent) {
47-
log := logrus.WithFields(logrus.Fields{
48-
"component": "logging_event_handler",
49-
"name": u.GetName(),
50-
"namespace": u.GetNamespace(),
51-
"gvk": u.GroupVersionKind().String(),
52-
"event_type": e.Event,
53-
})
5450
if l.LogLevel == Nothing {
5551
return
5652
}
57-
// log only the following for the 'Tasks' LogLevel
53+
54+
logger := log.WithValues(
55+
"component", "logging_event_handler",
56+
"name", u.GetName(),
57+
"namespace", u.GetNamespace(),
58+
"gvk", u.GroupVersionKind().String(),
59+
"event_type", e.Event,
60+
)
61+
62+
// logger only the following for the 'Tasks' LogLevel
5863
t, ok := e.EventData["task"]
5964
if ok {
6065
setFactAction := e.EventData["task_action"] == eventapi.TaskActionSetFact
6166
debugAction := e.EventData["task_action"] == eventapi.TaskActionDebug
6267

6368
if e.Event == eventapi.EventPlaybookOnTaskStart && !setFactAction && !debugAction {
64-
log.Infof("[playbook task]: %s", e.EventData["name"])
69+
logger.Info("[playbook task]", "EventData.Name", e.EventData["name"])
6570
return
6671
}
6772
if e.Event == eventapi.EventRunnerOnOk && debugAction {
68-
log.Infof("[playbook debug]: %v", e.EventData["task_args"])
73+
logger.V(log.VDebug).Info("[playbook debug]", "EventData.TaskArgs", e.EventData["task_args"])
6974
return
7075
}
7176
if e.Event == eventapi.EventRunnerOnFailed {
72-
log.Errorf("[failed]: [playbook task] '%s' failed with task_args - %v",
73-
t, e.EventData["task_args"])
77+
logger.Error(errors.New("[playbook task failed]"), "",
78+
"EventData.Task", t,
79+
"EventData.TaskArgs", e.EventData["task_args"],
80+
)
7481
return
7582
}
7683
}
84+
7785
// log everything else for the 'Everything' LogLevel
7886
if l.LogLevel == Everything {
79-
log.Infof("event: %#v", e.EventData)
87+
logger.Info("", "EventData", e.EventData)
8088
}
8189
}
8290

pkg/ansible/operator/operator.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@ import (
2020

2121
"github.com/operator-framework/operator-sdk/pkg/ansible/controller"
2222
"github.com/operator-framework/operator-sdk/pkg/ansible/runner"
23+
"github.com/operator-framework/operator-sdk/pkg/sdk/log"
24+
2325
"sigs.k8s.io/controller-runtime/pkg/manager"
2426
"sigs.k8s.io/controller-runtime/pkg/runtime/signals"
25-
26-
"github.com/sirupsen/logrus"
2727
)
2828

2929
// Run - A blocking function which starts a controller-runtime manager
@@ -32,7 +32,7 @@ import (
3232
func Run(done chan error, mgr manager.Manager, watchesPath string, reconcilePeriod time.Duration) {
3333
watches, err := runner.NewFromWatches(watchesPath)
3434
if err != nil {
35-
logrus.Error("Failed to get watches")
35+
log.Error(err, "Failed to get watches")
3636
done <- err
3737
return
3838
}

pkg/ansible/proxy/kubectl.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ package proxy
2222

2323
import (
2424
"fmt"
25-
"log"
2625
"net"
2726
"net/http"
2827
"net/url"
@@ -32,6 +31,8 @@ import (
3231
"syscall"
3332
"time"
3433

34+
"github.com/operator-framework/operator-sdk/pkg/sdk/log"
35+
3536
utilnet "k8s.io/apimachinery/pkg/util/net"
3637
k8sproxy "k8s.io/apimachinery/pkg/util/proxy"
3738
"k8s.io/client-go/rest"
@@ -91,15 +92,15 @@ func MakeRegexpArray(str string) ([]*regexp.Regexp, error) {
9192
func MakeRegexpArrayOrDie(str string) []*regexp.Regexp {
9293
result, err := MakeRegexpArray(str)
9394
if err != nil {
94-
log.Fatalf("error compiling re: %v", err)
95+
log.Fatal(err, "error compiling re")
9596
}
9697
return result
9798
}
9899

99100
func matchesRegexp(str string, regexps []*regexp.Regexp) bool {
100101
for _, re := range regexps {
101102
if re.MatchString(str) {
102-
log.Printf("%v matched %s", str, re)
103+
log.Info("matched found", "MatchString", str, "Regexp", re)
103104
return true
104105
}
105106
}
@@ -139,11 +140,11 @@ func extractHost(header string) (host string) {
139140
func (f *FilterServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
140141
host := extractHost(req.Host)
141142
if f.accept(req.Method, req.URL.Path, host) {
142-
log.Printf("Filter accepting %v %v %v", req.Method, req.URL.Path, host)
143+
log.Info("Filter acception", "Request.Method", req.Method, "Request.URL", req.URL.Path, "Host", host)
143144
f.delegate.ServeHTTP(rw, req)
144145
return
145146
}
146-
log.Printf("Filter rejecting %v %v %v", req.Method, req.URL.Path, host)
147+
log.Info("Filter rejection", "Request.Method", req.Method, "Request.URL", req.URL.Path, "Host", host)
147148
rw.WriteHeader(http.StatusForbidden)
148149
rw.Write([]byte("<h3>Unauthorized</h3>"))
149150
}
@@ -156,7 +157,7 @@ type server struct {
156157
type responder struct{}
157158

158159
func (r *responder) Error(w http.ResponseWriter, req *http.Request, err error) {
159-
log.Printf("Error while proxying request: %v", err)
160+
log.Error(err, "error while proxying request")
160161
http.Error(w, err.Error(), http.StatusInternalServerError)
161162
}
162163

pkg/ansible/proxy/proxy.go

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,14 @@ import (
2121
"bytes"
2222
"encoding/base64"
2323
"encoding/json"
24+
"errors"
25+
"fmt"
2426
"io/ioutil"
2527
"net/http"
2628
"net/http/httputil"
2729

28-
"github.com/sirupsen/logrus"
30+
"github.com/operator-framework/operator-sdk/pkg/sdk/log"
31+
2932
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
3033
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
3134
"k8s.io/client-go/rest"
@@ -37,53 +40,53 @@ import (
3740
func InjectOwnerReferenceHandler(h http.Handler) http.Handler {
3841
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
3942
if req.Method == http.MethodPost {
40-
logrus.Info("injecting owner reference")
43+
log.Info("injecting owner reference")
4144
dump, _ := httputil.DumpRequest(req, false)
42-
logrus.Debugf(string(dump))
45+
log.V(log.VDebug).Info("dumping request", "RequestDump", string(dump))
4346

4447
user, _, ok := req.BasicAuth()
4548
if !ok {
46-
logrus.Error("basic auth header not found")
49+
log.Error(errors.New("basic auth header not found"), "")
4750
w.Header().Set("WWW-Authenticate", "Basic realm=\"Operator Proxy\"")
4851
http.Error(w, "", http.StatusUnauthorized)
4952
return
5053
}
5154
authString, err := base64.StdEncoding.DecodeString(user)
5255
if err != nil {
5356
m := "could not base64 decode username"
54-
logrus.Errorf("%s", err.Error())
57+
log.Error(err, m)
5558
http.Error(w, m, http.StatusBadRequest)
5659
return
5760
}
5861
owner := metav1.OwnerReference{}
5962
json.Unmarshal(authString, &owner)
6063

61-
logrus.Debugf("%#+v", owner)
64+
log.V(log.VDebug).Info(fmt.Sprintf("%#+v", owner))
6265

6366
body, err := ioutil.ReadAll(req.Body)
6467
if err != nil {
6568
m := "could not read request body"
66-
logrus.Errorf("%s", err.Error())
69+
log.Error(err, m)
6770
http.Error(w, m, http.StatusInternalServerError)
6871
return
6972
}
7073
data := &unstructured.Unstructured{}
7174
err = json.Unmarshal(body, data)
7275
if err != nil {
7376
m := "could not deserialize request body"
74-
logrus.Errorf("%s", err.Error())
77+
log.Error(err, m)
7578
http.Error(w, m, http.StatusBadRequest)
7679
return
7780
}
7881
data.SetOwnerReferences(append(data.GetOwnerReferences(), owner))
7982
newBody, err := json.Marshal(data.Object)
8083
if err != nil {
8184
m := "could not serialize body"
82-
logrus.Errorf("%s", err.Error())
85+
log.Error(err, m)
8386
http.Error(w, m, http.StatusInternalServerError)
8487
return
8588
}
86-
logrus.Debugf(string(newBody))
89+
log.V(log.VDebug).Info("serialized body", "Body", string(newBody))
8790
req.Body = ioutil.NopCloser(bytes.NewBuffer(newBody))
8891
req.ContentLength = int64(len(newBody))
8992
}
@@ -128,7 +131,7 @@ func Run(done chan error, o Options) error {
128131
return err
129132
}
130133
go func() {
131-
logrus.Infof("Starting to serve on %s\n", l.Addr().String())
134+
log.Info("Starting to serve", "Address", l.Addr().String())
132135
done <- server.ServeOnListener(l)
133136
}()
134137
return nil

0 commit comments

Comments
 (0)