Skip to content

Commit a23f9e7

Browse files
authored
Merge pull request grafana#295 from HubertStefanski/fix-214
Fix-214- use zapper for logging and set log levels
2 parents db2b0eb + ceca764 commit a23f9e7

12 files changed

+47
-39
lines changed

cmd/manager/main.go

+11-7
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@ package main
22

33
import (
44
"context"
5-
"flag"
65
"fmt"
6+
"github.com/operator-framework/operator-sdk/pkg/log/zap"
7+
"github.com/spf13/pflag"
78
"os"
89
"runtime"
910
"strings"
@@ -52,14 +53,15 @@ func printVersion() {
5253
}
5354

5455
func init() {
55-
flagset := flag.CommandLine
56+
flagset := pflag.CommandLine
5657
flagset.StringVar(&flagImage, "grafana-image", "", "Overrides the default Grafana image")
5758
flagset.StringVar(&flagImageTag, "grafana-image-tag", "", "Overrides the default Grafana image tag")
5859
flagset.StringVar(&flagPluginsInitContainerImage, "grafana-plugins-init-container-image", "", "Overrides the default Grafana Plugins Init Container image")
5960
flagset.StringVar(&flagPluginsInitContainerTag, "grafana-plugins-init-container-tag", "", "Overrides the default Grafana Plugins Init Container tag")
6061
flagset.StringVar(&flagNamespaces, "namespaces", "", "Namespaces to scope the interaction of the Grafana operator. Mutually exclusive with --scan-all")
6162
flagset.StringVar(&flagJsonnetLocation, "jsonnet-location", "", "Overrides the base path of the jsonnet libraries")
6263
flagset.BoolVar(&scanAll, "scan-all", false, "Scans all namespaces for dashboards")
64+
flagset.AddFlagSet(zap.FlagSet())
6365
flagset.Parse(os.Args[1:])
6466
}
6567

@@ -113,7 +115,8 @@ func main() {
113115
// implementing the logr.Logger interface. This logger will
114116
// be propagated through the whole operator, generating
115117
// uniform and structured logs.
116-
logf.SetLogger(logf.ZapLogger(false))
118+
119+
logf.SetLogger(zap.Logger())
117120

118121
printVersion()
119122

@@ -144,7 +147,7 @@ func main() {
144147
var dashboardNamespaces = []string{namespace}
145148
if scanAll {
146149
dashboardNamespaces = []string{""}
147-
log.Info("Scanning for dashboards in all namespaces")
150+
log.V(1).Info("Scanning for dashboards in all namespaces")
148151
}
149152

150153
if flagNamespaces != "" {
@@ -153,7 +156,7 @@ func main() {
153156
fmt.Fprint(os.Stderr, "--namespaces provided but no valid namespaces in list")
154157
os.Exit(1)
155158
}
156-
log.Info(fmt.Sprintf("Scanning for dashboards in the following namespaces: [%s]", strings.Join(dashboardNamespaces, ",")))
159+
log.V(1).Info(fmt.Sprintf("Scanning for dashboards in the following namespaces: [%s]", strings.Join(dashboardNamespaces, ",")))
157160
}
158161

159162
// Get a config to talk to the apiserver
@@ -176,7 +179,7 @@ func main() {
176179
os.Exit(1)
177180
}
178181

179-
log.Info("Registering Components.")
182+
log.V(1).Info("Registering Components.")
180183

181184
// Starting the resource auto-detection for the grafana controller
182185
autodetect, err := common.NewAutoDetect(mgr)
@@ -214,11 +217,12 @@ func main() {
214217
},
215218
}
216219
_, err = metrics.CreateMetricsService(context.TODO(), cfg, servicePorts)
220+
217221
if err != nil {
218222
log.Error(err, "error starting metrics service")
219223
}
220224

221-
log.Info("Starting the Cmd.")
225+
log.V(1).Info("Starting the Cmd.")
222226

223227
signalHandler := signals.SetupSignalHandler()
224228

documentation/deploy_grafana.md

+5-2
Original file line numberDiff line numberDiff line change
@@ -115,13 +115,16 @@ The operator accepts a number of flags that can be passed in the `args` section
115115

116116
* `--grafonnet-location`: overrides the location of the grafonnet library. Defaults to `/opt/grafonnet-lib`. Only useful when running the operator locally.
117117

118-
* `--scan-all`: watch for dashboards in all namespaces. This requires the the operator service account to have cluster wide permissions to `get`, `list`, `update` and `watch` dashboards. See `deploy/cluster_roles`.
118+
* `--scan-all`: watch for dashboards in all namespaces. This requires the operator service account to have cluster wide permissions to `get`, `list`, `update` and `watch` dashboards. See `deploy/cluster_roles`.
119119

120120
* `--namespaces`: watch for dashboards in a list of namespaces. Mutually exclusive with `--scan-all`.
121121

122+
* `--zap-level=n`: set the logging level for the operator, leaving out this flag will only log Errors and error related info, current options are:
123+
- `--zap-level=1`: show all Info level logs
124+
122125
See `deploy/operator.yaml` for an example.
123126

124-
If using the automated Ansible installer see the [grafana-operator-namespace-resources.yaml - Parameters](../deploy/ansible/README.md#parameters-1) for the equivlant parameters.
127+
If using the automated Ansible installer see the [grafana-operator-namespace-resources.yaml - Parameters](../deploy/ansible/README.md#parameters-1) for the equivalent parameters.
125128

126129
## Deploying Grafana
127130

go.mod

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ require (
1010
github.com/openshift/api v3.9.0+incompatible
1111
github.com/operator-framework/operator-sdk v0.18.2
1212
github.com/pkg/errors v0.9.1
13+
github.com/spf13/pflag v1.0.5
1314
k8s.io/api v0.18.2
1415
k8s.io/apimachinery v0.18.2
1516
k8s.io/client-go v12.0.0+incompatible

pkg/controller/common/clusterActions.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,10 @@ func (i *ClusterActionRunner) RunAll(desiredState DesiredClusterState) error {
7575
for index, action := range desiredState {
7676
msg, err := action.Run(i)
7777
if err != nil {
78-
i.log.Info(fmt.Sprintf("(%5d) %10s %s", index, "FAILED", msg))
78+
i.log.V(1).Info(fmt.Sprintf("(%5d) %10s %s", index, "FAILED", msg))
7979
return err
8080
}
81-
i.log.Info(fmt.Sprintf("(%5d) %10s %s", index, "SUCCESS", msg))
81+
i.log.V(1).Info(fmt.Sprintf("(%5d) %10s %s", index, "SUCCESS", msg))
8282
}
8383

8484
return nil
@@ -100,10 +100,11 @@ func (i *ClusterActionRunner) exposeSecret(ns string, ref *v14.SecretEnvSource,
100100
for secretKey, secretValue := range secret.Data {
101101
if exposedVar == secretKey {
102102
os.Setenv(secretKey, string(secretValue))
103-
i.log.Info(fmt.Sprintf("found value for %s in secret %s", exposedVar, ref.Name))
103+
i.log.V(1).Info("found value for %s in secret %s", exposedVar, ref.Name)
104104
}
105105
}
106106
}
107+
107108
return nil
108109
}
109110

@@ -123,7 +124,7 @@ func (i *ClusterActionRunner) exposeConfigMap(ns string, ref *v14.ConfigMapEnvSo
123124
for configMapKey, configMapValue := range configMap.Data {
124125
if exposedVar == configMapKey {
125126
os.Setenv(configMapKey, string(configMapValue))
126-
i.log.Info(fmt.Sprintf("found value for %s in config map %s", exposedVar, ref.Name))
127+
i.log.V(1).Info("found value for %s in config map %s", exposedVar, ref.Name)
127128
}
128129
}
129130
}

pkg/controller/grafana/grafana_controller.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler, autodetectChannel chan sch
102102
log.Error(err, fmt.Sprintf("error adding secondary watch for %v", common.RouteKind))
103103
} else {
104104
cfg.AddConfigItem(config.ConfigRouteWatch, true)
105-
log.Info(fmt.Sprintf("added secondary watch for %v", common.RouteKind))
105+
log.V(1).Info("added secondary watch for %v", common.RouteKind)
106106
}
107107
}
108108
}
@@ -295,7 +295,7 @@ func (r *ReconcileGrafana) manageSuccess(cr *grafanav1alpha1.Grafana, state *com
295295

296296
common.ControllerEvents <- controllerState
297297

298-
log.Info("desired cluster state met")
298+
log.V(1).Info("desired cluster state met")
299299

300300
return reconcile.Result{RequeueAfter: config.RequeueDelay}, nil
301301
}

pkg/controller/grafana/grafana_reconciler.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -333,12 +333,12 @@ func (i *GrafanaReconciler) reconcilePlugins(cr *v1alpha1.Grafana, plugins v1alp
333333

334334
for _, plugin := range plugins {
335335
if i.Plugins.PluginExists(plugin) == false {
336-
log.Info(fmt.Sprintf("invalid plugin: %s@%s", plugin.Name, plugin.Version))
336+
log.V(1).Info("invalid plugin: %s@%s", plugin.Name, plugin.Version)
337337
failedPlugins = append(failedPlugins, plugin)
338338
continue
339339
}
340340

341-
log.Info(fmt.Sprintf("installing plugin: %s@%s", plugin.Name, plugin.Version))
341+
log.V(1).Info("installing plugin: %s@%s", plugin.Name, plugin.Version)
342342
validPlugins = append(validPlugins, plugin)
343343
}
344344

pkg/controller/grafana/grafonnet_utils.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ func reconcileConfigMaps(cr *grafanav1alpha1.Grafana, r *ReconcileGrafana) error
5757
if err != nil {
5858
return err
5959
}
60-
log.Info(fmt.Sprintf("imported jsonnet library %v", filePath))
60+
log.V(1).Info(fmt.Sprintf("imported jsonnet library %v", filePath))
6161
}
6262
}
6363
return nil

pkg/controller/grafana/pluginsHelper.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ func (h *PluginsHelperImpl) FilterPlugins(cr *grafanav1alpha1.Grafana, requested
9797
// Don't allow to install multiple versions of the same plugin
9898
if filteredPlugins.HasSomeVersionOf(&plugin) == true {
9999
installedVersion := filteredPlugins.GetInstalledVersionOf(&plugin)
100-
log.Info(fmt.Sprintf("not installing version %s of %s because %s is already installed", plugin.Version, plugin.Name, installedVersion.Version))
100+
log.V(1).Info(fmt.Sprintf("not installing version %s of %s because %s is already installed", plugin.Version, plugin.Name, installedVersion.Version))
101101
continue
102102
}
103103

@@ -115,7 +115,7 @@ func (h *PluginsHelperImpl) FilterPlugins(cr *grafanav1alpha1.Grafana, requested
115115
// New plugin
116116
if cr.Status.InstalledPlugins.HasSomeVersionOf(&plugin) == false {
117117
filteredPlugins = append(filteredPlugins, plugin)
118-
log.Info(fmt.Sprintf("installing plugin %s@%s", plugin.Name, plugin.Version))
118+
log.V(1).Info(fmt.Sprintf("installing plugin %s@%s", plugin.Name, plugin.Version))
119119
pluginsUpdated = true
120120
continue
121121
}
@@ -130,7 +130,7 @@ func (h *PluginsHelperImpl) FilterPlugins(cr *grafanav1alpha1.Grafana, requested
130130
requested.VersionsOf(&plugin) == 1 {
131131
installedVersion := cr.Status.InstalledPlugins.GetInstalledVersionOf(&plugin)
132132
filteredPlugins = append(filteredPlugins, plugin)
133-
log.Info(fmt.Sprintf("changing version of plugin %s form %s to %s", plugin.Name, installedVersion.Version, plugin.Version))
133+
log.V(1).Info(fmt.Sprintf("changing version of plugin %s form %s to %s", plugin.Name, installedVersion.Version, plugin.Version))
134134
pluginsUpdated = true
135135
continue
136136
}

pkg/controller/grafanadashboard/dashboard_controller.go

+10-11
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler, namespace string) error {
6363
// Watch for changes to primary resource GrafanaDashboard
6464
err = c.Watch(&source.Kind{Type: &grafanav1alpha1.GrafanaDashboard{}}, &handler.EnqueueRequestForObject{})
6565
if err == nil {
66-
log.Info("Starting dashboard controller")
66+
log.V(1).Info("Starting dashboard controller")
6767
}
6868

6969
ref := r.(*ReconcileGrafanaDashboard)
@@ -80,7 +80,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler, namespace string) error {
8080

8181
go func() {
8282
for range ticker.C {
83-
log.Info("running periodic dashboard resync")
83+
log.V(1).Info("running periodic dashboard resync")
8484
sendEmptyRequest()
8585
}
8686
}()
@@ -113,7 +113,7 @@ func (r *ReconcileGrafanaDashboard) Reconcile(request reconcile.Request) (reconc
113113

114114
// If Grafana is not running there is no need to continue
115115
if !r.state.GrafanaReady {
116-
log.Info("no grafana instance available")
116+
log.V(1).Info("no grafana instance available")
117117
return reconcile.Result{Requeue: false}, nil
118118
}
119119

@@ -141,7 +141,7 @@ func (r *ReconcileGrafanaDashboard) Reconcile(request reconcile.Request) (reconc
141141

142142
if errors.IsNotFound(err) {
143143
// If some dashboard has been deleted, then always re sync the world
144-
log.Info(fmt.Sprintf("deleting dashboard %v/%v", request.Namespace, request.Name))
144+
log.V(1).Info(fmt.Sprintf("deleting dashboard %v/%v", request.Namespace, request.Name))
145145
return r.reconcileDashboards(request, client)
146146
}
147147
// Error reading the object - requeue the request.
@@ -151,7 +151,7 @@ func (r *ReconcileGrafanaDashboard) Reconcile(request reconcile.Request) (reconc
151151
// If the dashboard does not match the label selectors then we ignore it
152152
cr := instance.DeepCopy()
153153
if !r.isMatch(cr) {
154-
log.Info(fmt.Sprintf("dashboard %v/%v found but selectors do not match",
154+
log.V(1).Info(fmt.Sprintf("dashboard %v/%v found but selectors do not match",
155155
cr.Namespace, cr.Name))
156156
return reconcile.Result{}, nil
157157
}
@@ -223,14 +223,13 @@ func (r *ReconcileGrafanaDashboard) reconcileDashboards(request reconcile.Reques
223223
if !inNamespace(dashboard) {
224224
dashboardsToDelete = append(dashboardsToDelete, dashboard)
225225
}
226-
227226
}
228227

229228
// Process new/updated dashboards
230229
for _, dashboard := range namespaceDashboards.Items {
231230
// Is this a dashboard we care about (matches the label selectors)?
232231
if !r.isMatch(&dashboard) {
233-
log.Info(fmt.Sprintf("dashboard %v/%v found but selectors do not match",
232+
log.V(1).Info(fmt.Sprintf("dashboard %v/%v found but selectors do not match",
234233
dashboard.Namespace, dashboard.Name))
235234
continue
236235
}
@@ -281,7 +280,7 @@ func (r *ReconcileGrafanaDashboard) reconcileDashboards(request reconcile.Reques
281280
}
282281

283282
if matchesNamespaceLabels == false {
284-
log.Info(fmt.Sprintf("dashboard %v skipped because the namespace labels do not match", dashboard.Name))
283+
log.V(1).Info(fmt.Sprintf("dashboard %v skipped because the namespace labels do not match", dashboard.Name))
285284
continue
286285
}
287286
}
@@ -307,7 +306,7 @@ func (r *ReconcileGrafanaDashboard) reconcileDashboards(request reconcile.Reques
307306
*status.Message))
308307
}
309308

310-
log.Info(fmt.Sprintf("delete result was %v", *status.Message))
309+
log.V(1).Info(fmt.Sprintf("delete result was %v", *status.Message))
311310

312311
r.config.RemovePluginsFor(dashboard.Namespace, dashboard.Name)
313312
r.config.RemoveDashboard(dashboard.Namespace, dashboard.Name)
@@ -322,7 +321,7 @@ func (r *ReconcileGrafanaDashboard) reconcileDashboards(request reconcile.Reques
322321
// Check for empty managed folders (namespace-named) and delete obsolete ones
323322
if dashboard.FolderName == "" || dashboard.FolderName == dashboard.Namespace {
324323
if safe := grafanaClient.SafeToDelete(knownDashboards, dashboard.FolderId); !safe {
325-
log.Info("folder cannot be deleted as it's being used by other dashboards")
324+
log.V(1).Info("folder cannot be deleted as it's being used by other dashboards")
326325
break
327326
}
328327
if err = grafanaClient.DeleteFolder(dashboard.FolderId); err != nil {
@@ -342,7 +341,7 @@ func (r *ReconcileGrafanaDashboard) manageSuccess(dashboard *grafanav1alpha1.Gra
342341
dashboard.Namespace,
343342
dashboard.Name)
344343
r.recorder.Event(dashboard, "Normal", "Success", msg)
345-
log.Info(msg)
344+
log.V(1).Info(msg)
346345
r.config.AddDashboard(dashboard, folderId, folderName)
347346
r.config.SetPluginsFor(dashboard)
348347
}

pkg/controller/grafanadashboard/dashboard_pipeline.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -253,13 +253,13 @@ func (r *DashboardPipelineImpl) resolveDatasources() error {
253253
for _, input := range r.Dashboard.Spec.Datasources {
254254
if input.DatasourceName == "" || input.InputName == "" {
255255
msg := fmt.Sprintf("invalid datasource input rule, input or datasource empty")
256-
r.Logger.Info(msg)
256+
r.Logger.V(1).Info(msg)
257257
return errors.New(msg)
258258
}
259259

260260
searchValue := fmt.Sprintf("${%s}", input.InputName)
261261
currentJson = strings.ReplaceAll(currentJson, searchValue, input.DatasourceName)
262-
r.Logger.Info(fmt.Sprintf("resolving input %s to %s", input.InputName, input.DatasourceName))
262+
r.Logger.V(1).Info(fmt.Sprintf("resolving input %s to %s", input.InputName, input.DatasourceName))
263263
}
264264

265265
r.JSON = currentJson

pkg/controller/grafanadashboard/grafana_client.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ func (r *GrafanaClientImpl) DeleteFolder(deleteID *int64) error {
415415
}
416416

417417
err = json.Unmarshal(data, &response)
418-
log.Info(fmt.Sprintf("delete result was %v", *response.Message))
418+
log.V(1).Info(fmt.Sprintf("delete result was %v", *response.Message))
419419

420420
return err
421421
}

pkg/controller/grafanadatasource/datasource_controller.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler, namespace string) error {
8585

8686
go func() {
8787
for range ticker.C {
88-
log.Info("running periodic datasource resync")
88+
log.V(1).Info("running periodic datasource resync")
8989
sendEmptyRequest()
9090
}
9191
}()
@@ -126,7 +126,7 @@ func (r *ReconcileGrafanaDataSource) Reconcile(request reconcile.Request) (recon
126126
}
127127

128128
if currentState.KnownDataSources == nil {
129-
log.Info(fmt.Sprintf("no datasources configmap found"))
129+
log.V(1).Info(fmt.Sprintf("no datasources configmap found"))
130130
return reconcile.Result{Requeue: false}, nil
131131
}
132132

@@ -170,7 +170,7 @@ func (r *ReconcileGrafanaDataSource) reconcileDataSources(state *common.DataSour
170170

171171
// apply dataSourcesToDelete
172172
for _, ds := range dataSourcesToDelete {
173-
log.Info(fmt.Sprintf("deleting datasource %v", ds))
173+
log.V(1).Info(fmt.Sprintf("deleting datasource %v", ds))
174174
if state.KnownDataSources.Data != nil {
175175
delete(state.KnownDataSources.Data, ds)
176176
}
@@ -269,7 +269,7 @@ func (r *ReconcileGrafanaDataSource) manageError(datasource *grafanav1alpha1.Gra
269269
// is updated
270270
func (r *ReconcileGrafanaDataSource) manageSuccess(datasources []grafanav1alpha1.GrafanaDataSource) {
271271
for _, datasource := range datasources {
272-
log.Info(fmt.Sprintf("datasource %v/%v successfully imported",
272+
log.V(1).Info(fmt.Sprintf("datasource %v/%v successfully imported",
273273
datasource.Namespace,
274274
datasource.Name))
275275

0 commit comments

Comments
 (0)