Skip to content

Commit 4bb1b38

Browse files
authored
Merge pull request #1807 from dmpe/strcuturedlogging_part1
feat(logging): migration to structure logging for main.go, pkg/ & internal/ folders
2 parents 9063fa6 + ebb8b10 commit 4bb1b38

File tree

7 files changed

+37
-34
lines changed

7 files changed

+37
-34
lines changed

internal/store/builder.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ func (b *Builder) WithCustomResourceStoreFactories(fs ...customresource.Registry
178178
for i := range fs {
179179
f := fs[i]
180180
if _, ok := availableStores[f.Name()]; ok {
181-
klog.Warningf("The internal resource store named %s already exists and is overridden by a custom resource store with the same name, please make sure it meets your expectation", f.Name())
181+
klog.InfoS("The internal resource store already exists and is overridden by a custom resource store with the same name, please make sure it meets your expectation", "registryName", f.Name())
182182
}
183183
availableStores[f.Name()] = func(b *Builder) []cache.Store {
184184
return b.buildCustomResourceStoresFunc(
@@ -230,7 +230,7 @@ func (b *Builder) Build() []metricsstore.MetricsWriter {
230230
}
231231
}
232232

233-
klog.Infof("Active resources: %s", strings.Join(activeStoreNames, ","))
233+
klog.InfoS("Active resources", "activeStoreNames", strings.Join(activeStoreNames, ","))
234234

235235
return metricsWriters
236236
}
@@ -255,7 +255,7 @@ func (b *Builder) BuildStores() [][]cache.Store {
255255
}
256256
}
257257

258-
klog.Infof("Active resources: %s", strings.Join(activeStoreNames, ","))
258+
klog.InfoS("Active resources", "activeStoreNames", strings.Join(activeStoreNames, ","))
259259

260260
return allStores
261261
}
@@ -483,7 +483,7 @@ func (b *Builder) buildCustomResourceStores(resourceName string,
483483

484484
customResourceClient, ok := b.customResourceClients[resourceName]
485485
if !ok {
486-
klog.Warningf("Custom resource client %s does not exist", resourceName)
486+
klog.InfoS("Custom resource client does not exist", "resourceName", resourceName)
487487
return []cache.Store{}
488488
}
489489

main.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ func main() {
3838
opts.AddFlags()
3939

4040
if err := opts.Parse(); err != nil {
41-
klog.Fatalf("Parsing flag definitions error: %v", err)
41+
klog.ErrorS(err, "Parsing flag definitions error")
42+
klog.FlushAndExit(klog.ExitFlushTimeout, 1)
4243
}
4344

4445
if opts.Version {
@@ -55,14 +56,16 @@ func main() {
5556
if config, set := resolveCustomResourceConfig(opts); set {
5657
crf, err := customresourcestate.FromConfig(config)
5758
if err != nil {
58-
klog.Fatal(err)
59+
klog.ErrorS(err, "Parsing from Custom Resource State Metrics file failed")
60+
klog.FlushAndExit(klog.ExitFlushTimeout, 1)
5961
}
6062
factories = append(factories, crf...)
6163
}
6264

6365
ctx := context.Background()
6466
if err := app.RunKubeStateMetrics(ctx, opts, factories...); err != nil {
65-
klog.Fatalf("Failed to run kube-state-metrics: %v", err)
67+
klog.ErrorS(err, "Failed to run kube-state-metrics")
68+
klog.FlushAndExit(klog.ExitFlushTimeout, 1)
6669
}
6770
}
6871

@@ -73,7 +76,8 @@ func resolveCustomResourceConfig(opts *options.Options) (customresourcestate.Con
7376
if file := opts.CustomResourceConfigFile; file != "" {
7477
f, err := os.Open(file)
7578
if err != nil {
76-
klog.Fatal(err)
79+
klog.ErrorS(err, "Custom Resource State Metrics file could not be opened")
80+
klog.FlushAndExit(klog.ExitFlushTimeout, 1)
7781
}
7882
return yaml.NewDecoder(f), true
7983
}

pkg/app/server.go

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -89,14 +89,14 @@ func RunKubeStateMetrics(ctx context.Context, opts *options.Options, factories .
8989

9090
var resources []string
9191
if len(opts.Resources) == 0 {
92-
klog.Info("Using default resources")
92+
klog.InfoS("Used default resources")
9393
resources = options.DefaultResources.AsSlice()
9494
// enable custom resource
9595
for _, factory := range factories {
9696
resources = append(resources, factory.Name())
9797
}
9898
} else {
99-
klog.Infof("Using resources %s", opts.Resources.String())
99+
klog.InfoS("Used resources", "resources", opts.Resources.String())
100100
resources = opts.Resources.AsSlice()
101101
}
102102

@@ -118,15 +118,15 @@ func RunKubeStateMetrics(ctx context.Context, opts *options.Options, factories .
118118
return fmt.Errorf("error initializing the allowdeny list: %v", err)
119119
}
120120

121-
klog.Infof("Metric allow-denylisting: %v", allowDenyList.Status())
121+
klog.InfoS("Metric allow-denylisting", "allowDenyStatus", allowDenyList.Status())
122122

123123
optInMetricFamilyFilter, err := optin.NewMetricFamilyFilter(opts.MetricOptInList)
124124
if err != nil {
125125
return fmt.Errorf("error initializing the opt-in metric list: %v", err)
126126
}
127127

128128
if optInMetricFamilyFilter.Count() > 0 {
129-
klog.Infof("Metrics which were opted into: %v", optInMetricFamilyFilter.Status())
129+
klog.InfoS("Metrics which were opted into", "optInMetricsFamilyStatus", optInMetricFamilyFilter.Status())
130130
}
131131

132132
storeBuilder.WithFamilyGeneratorFilter(generator.NewCompositeFamilyGeneratorFilter(
@@ -187,7 +187,7 @@ func RunKubeStateMetrics(ctx context.Context, opts *options.Options, factories .
187187
// Run Telemetry server
188188
{
189189
g.Add(func() error {
190-
klog.Infof("Starting kube-state-metrics self metrics server: %s", telemetryListenAddress)
190+
klog.InfoS("Started kube-state-metrics self metrics server", "telemetryAddress", telemetryListenAddress)
191191
return web.ListenAndServe(&telemetryServer, tlsConfig, promLogger)
192192
}, func(error) {
193193
ctxShutDown, cancel := context.WithTimeout(ctx, 3*time.Second)
@@ -198,7 +198,7 @@ func RunKubeStateMetrics(ctx context.Context, opts *options.Options, factories .
198198
// Run Metrics server
199199
{
200200
g.Add(func() error {
201-
klog.Infof("Starting metrics server: %s", metricsServerListenAddress)
201+
klog.InfoS("Started metrics server", "metricsServerAddress", metricsServerListenAddress)
202202
return web.ListenAndServe(&metricsServer, tlsConfig, promLogger)
203203
}, func(error) {
204204
ctxShutDown, cancel := context.WithTimeout(ctx, 3*time.Second)
@@ -210,7 +210,7 @@ func RunKubeStateMetrics(ctx context.Context, opts *options.Options, factories .
210210
if err := g.Run(); err != nil {
211211
return fmt.Errorf("run server group error: %v", err)
212212
}
213-
klog.Info("Exiting")
213+
klog.InfoS("Exited")
214214
return nil
215215
}
216216

@@ -246,14 +246,13 @@ func createKubeClient(apiserver string, kubeconfig string, factories ...customre
246246
// Informers don't seem to do a good job logging error messages when it
247247
// can't reach the server, making debugging hard. This makes it easier to
248248
// figure out if apiserver is configured incorrectly.
249-
klog.Infof("Testing communication with server")
249+
klog.InfoS("Tested communication with server")
250250
v, err := kubeClient.Discovery().ServerVersion()
251251
if err != nil {
252252
return nil, nil, nil, fmt.Errorf("error while trying to communicate with apiserver: %w", err)
253253
}
254-
klog.Infof("Running with Kubernetes cluster version: v%s.%s. git version: %s. git tree state: %s. commit: %s. platform: %s",
255-
v.Major, v.Minor, v.GitVersion, v.GitTreeState, v.GitCommit, v.Platform)
256-
klog.Infof("Communication with server successful")
254+
klog.InfoS("Run with Kubernetes cluster version", "major", v.Major, "minor", v.Minor, "gitVersion", v.GitVersion, "gitTreeState", v.GitTreeState, "gitCommit", v.GitCommit, "platform", v.Platform)
255+
klog.InfoS("Communication with server successful")
257256

258257
return kubeClient, vpaClient, customResourceClients, nil
259258
}

pkg/customresourcestate/registry_factory.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,7 @@ func compilePath(path []string) (out valuePath, _ error) {
440440
}
441441

442442
func (s fieldMetrics) MetricFamilyGenerators(_, _ []string) (result []generator.FamilyGenerator) {
443-
klog.Infof("custom resource state adding metrics: %v", s.names())
443+
klog.InfoS("Custom resource state added metrics", "familyNames", s.names())
444444
for _, f := range s.Families {
445445
result = append(result, famGen(f))
446446
}
@@ -461,7 +461,7 @@ func famGen(f compiledFamily) generator.FamilyGenerator {
461461
}
462462

463463
func generate(u *unstructured.Unstructured, f compiledFamily, errLog klog.Verbose) *metric.Family {
464-
klog.V(10).Infof("%s: checking %s", f.Name, u.GetName())
464+
klog.V(10).InfoS("Checked", "compiledFamilyName", f.Name, "unstructuredName", u.GetName())
465465
var metrics []*metric.Metric
466466
baseLabels := f.BaseLabels(u.Object)
467467
values, errors := f.Each.Values(u.Object)
@@ -474,7 +474,7 @@ func generate(u *unstructured.Unstructured, f compiledFamily, errLog klog.Verbos
474474
v.DefaultLabels(baseLabels)
475475
metrics = append(metrics, v.ToMetric())
476476
}
477-
klog.V(10).Infof("%s: produced %d metrics for %s", f.Name, len(metrics), u.GetName())
477+
klog.V(10).InfoS("Produced metrics for", "compiledFamilyName", f.Name, "metricsLength", len(metrics), "unstructuredName", u.GetName())
478478

479479
return &metric.Family{
480480
Metrics: metrics,

pkg/metricshandler/metrics_handler.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ func (m *MetricsHandler) ConfigureSharding(ctx context.Context, shard int32, tot
7777
m.cancel()
7878
}
7979
if totalShards != 1 {
80-
klog.Infof("configuring sharding of this instance to be shard index %d (zero-indexed) out of %d total shards", shard, totalShards)
80+
klog.InfoS("Configuring sharding of this instance to be shard index (zero-indexed) out of total shards", "shard", shard, "totalShards", totalShards)
8181
}
8282
ctx, m.cancel = context.WithCancel(ctx)
8383
m.storeBuilder.WithSharding(shard, totalShards)
@@ -94,14 +94,14 @@ func (m *MetricsHandler) Run(ctx context.Context) error {
9494
autoSharding := len(m.opts.Pod) > 0 && len(m.opts.Namespace) > 0
9595

9696
if !autoSharding {
97-
klog.Info("Autosharding disabled")
97+
klog.InfoS("Autosharding disabled")
9898
m.ConfigureSharding(ctx, m.opts.Shard, m.opts.TotalShards)
9999
<-ctx.Done()
100100
return ctx.Err()
101101
}
102102

103-
klog.Infof("Autosharding enabled with pod=%v pod_namespace=%v", m.opts.Pod, m.opts.Namespace)
104-
klog.Infof("Auto detecting sharding settings.")
103+
klog.InfoS("Autosharding enabled with pod", "pod", klog.KRef(m.opts.Namespace, m.opts.Pod))
104+
klog.InfoS("Auto detecting sharding settings")
105105
ss, err := detectStatefulSet(m.kubeClient, m.opts.Pod, m.opts.Namespace)
106106
if err != nil {
107107
return fmt.Errorf("detect StatefulSet: %w", err)
@@ -125,7 +125,7 @@ func (m *MetricsHandler) Run(ctx context.Context) error {
125125

126126
shard, totalShards, err := shardingSettingsFromStatefulSet(ss, m.opts.Pod)
127127
if err != nil {
128-
klog.Errorf("detect sharding settings from StatefulSet: %v", err)
128+
klog.ErrorS(err, "Detected sharding settings from StatefulSet")
129129
return
130130
}
131131

@@ -152,7 +152,7 @@ func (m *MetricsHandler) Run(ctx context.Context) error {
152152

153153
shard, totalShards, err := shardingSettingsFromStatefulSet(cur, m.opts.Pod)
154154
if err != nil {
155-
klog.Errorf("detect sharding settings from StatefulSet: %v", err)
155+
klog.ErrorS(err, "Detected sharding settings from StatefulSet")
156156
return
157157
}
158158

pkg/options/types.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,13 +133,13 @@ func (n *NamespaceList) Set(value string) error {
133133
func (n *NamespaceList) GetNamespaces() NamespaceList {
134134
ns := *n
135135
if len(*n) == 0 {
136-
klog.Info("Using all namespace")
136+
klog.InfoS("Using all namespaces")
137137
ns = DefaultNamespaces
138138
} else {
139139
if n.IsAllNamespaces() {
140-
klog.Info("Using all namespace")
140+
klog.InfoS("Using all namespaces")
141141
} else {
142-
klog.Infof("Using %s namespaces", ns)
142+
klog.InfoS("Using namespaces", "nameSpaces", ns)
143143
}
144144
}
145145
return ns

pkg/util/proc/reaper.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,22 +31,22 @@ import (
3131
// that has pid 1.
3232
func StartReaper() {
3333
if os.Getpid() == 1 {
34-
klog.V(4).Infof("Launching reaper")
34+
klog.V(4).InfoS("Launching reaper")
3535
go func() {
3636
sigs := make(chan os.Signal, 1)
3737
signal.Notify(sigs, syscall.SIGCHLD)
3838
for {
3939
// Wait for a child to terminate
4040
sig := <-sigs
41-
klog.V(4).Infof("Signal received: %v", sig)
41+
klog.V(4).InfoS("Signal received", "signal", sig)
4242
for {
4343
// Reap processes
4444
cpid, _ := syscall.Wait4(-1, nil, syscall.WNOHANG, nil)
4545
if cpid < 1 {
4646
break
4747
}
4848

49-
klog.V(4).Infof("Reaped process with pid %d", cpid)
49+
klog.V(4).InfoS("Reaped process with pid", "cpid", cpid)
5050
}
5151
}
5252
}()

0 commit comments

Comments
 (0)