Skip to content

Commit db85067

Browse files
committed
use our own logger instance instead of the standard logger
Signed-off-by: Tim Ramlot <[email protected]>
1 parent 473277b commit db85067

File tree

6 files changed

+69
-61
lines changed

6 files changed

+69
-61
lines changed

cmd/agent.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ package cmd
33
import (
44
"fmt"
55
"io/ioutil"
6-
"log"
76
"os"
87
"time"
98

109
"github.com/jetstack/preflight/pkg/agent"
10+
"github.com/jetstack/preflight/pkg/logs"
1111
"github.com/jetstack/preflight/pkg/permissions"
1212
"github.com/spf13/cobra"
1313
)
@@ -39,11 +39,11 @@ var agentRBACCmd = &cobra.Command{
3939

4040
b, err := ioutil.ReadFile(agent.ConfigFilePath)
4141
if err != nil {
42-
log.Fatalf("Failed to read config file: %s", err)
42+
logs.Log.Fatalf("Failed to read config file: %s", err)
4343
}
4444
config, err := agent.ParseConfig(b, false)
4545
if err != nil {
46-
log.Fatalf("Failed to parse config file: %s", err)
46+
logs.Log.Fatalf("Failed to parse config file: %s", err)
4747
}
4848

4949
out := permissions.GenerateFullManifest(config.DataGatherers)

pkg/agent/run.go

Lines changed: 49 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"fmt"
88
"io"
99
"io/ioutil"
10-
"log"
1110
"net/http"
1211
_ "net/http/pprof"
1312
"net/url"
@@ -18,6 +17,7 @@ import (
1817

1918
"github.com/cenkalti/backoff"
2019
"github.com/hashicorp/go-multierror"
20+
"github.com/jetstack/preflight/pkg/logs"
2121
json "github.com/json-iterator/go"
2222
"github.com/prometheus/client_golang/prometheus"
2323
"github.com/prometheus/client_golang/prometheus/promhttp"
@@ -86,23 +86,23 @@ func Run(cmd *cobra.Command, args []string) {
8686
config, preflightClient := getConfiguration()
8787

8888
if Profiling {
89-
log.Printf("pprof profiling was enabled.\nRunning profiling on port :6060")
89+
logs.Log.Printf("pprof profiling was enabled.\nRunning profiling on port :6060")
9090
go func() {
9191
err := http.ListenAndServe(":6060", nil)
9292
if err != nil && !errors.Is(err, http.ErrServerClosed) {
93-
log.Fatalf("failed to run pprof profiler: %s", err)
93+
logs.Log.Fatalf("failed to run pprof profiler: %s", err)
9494
}
9595
}()
9696
}
9797
if Prometheus {
98-
log.Printf("Prometheus was enabled.\nRunning prometheus server on port :8081")
98+
logs.Log.Printf("Prometheus was enabled.\nRunning prometheus server on port :8081")
9999
go func() {
100100
prometheus.MustRegister(metricPayloadSize)
101101
metricsServer := http.NewServeMux()
102102
metricsServer.Handle("/metrics", promhttp.Handler())
103103
err := http.ListenAndServe(":8081", metricsServer)
104104
if err != nil && !errors.Is(err, http.ErrServerClosed) {
105-
log.Fatalf("failed to run prometheus server: %s", err)
105+
logs.Log.Fatalf("failed to run prometheus server: %s", err)
106106
}
107107
}()
108108
}
@@ -115,19 +115,19 @@ func Run(cmd *cobra.Command, args []string) {
115115
kind := dgConfig.Kind
116116
if dgConfig.DataPath != "" {
117117
kind = "local"
118-
log.Fatalf("running data gatherer %s of type %s as Local, data-path override present: %s", dgConfig.Name, dgConfig.Kind, dgConfig.DataPath)
118+
logs.Log.Fatalf("running data gatherer %s of type %s as Local, data-path override present: %s", dgConfig.Name, dgConfig.Kind, dgConfig.DataPath)
119119
}
120120

121121
newDg, err := dgConfig.Config.NewDataGatherer(ctx)
122122
if err != nil {
123-
log.Fatalf("failed to instantiate %q data gatherer %q: %v", kind, dgConfig.Name, err)
123+
logs.Log.Fatalf("failed to instantiate %q data gatherer %q: %v", kind, dgConfig.Name, err)
124124
}
125125

126-
log.Printf("starting %q datagatherer", dgConfig.Name)
126+
logs.Log.Printf("starting %q datagatherer", dgConfig.Name)
127127

128128
// start the data gatherers and wait for the cache sync
129129
if err := newDg.Run(ctx.Done()); err != nil {
130-
log.Printf("failed to start %q data gatherer %q: %v", kind, dgConfig.Name, err)
130+
logs.Log.Printf("failed to start %q data gatherer %q: %v", kind, dgConfig.Name, err)
131131
}
132132

133133
// bootCtx is a context with a timeout to allow the informer 5
@@ -142,7 +142,7 @@ func Run(cmd *cobra.Command, args []string) {
142142
// the run.
143143
if err := newDg.WaitForCacheSync(bootCtx.Done()); err != nil {
144144
// log sync failure, this might recover in future
145-
log.Printf("failed to complete initial sync of %q data gatherer %q: %v", kind, dgConfig.Name, err)
145+
logs.Log.Printf("failed to complete initial sync of %q data gatherer %q: %v", kind, dgConfig.Name, err)
146146
}
147147

148148
// regardless of success, this dataGatherers has been given a
@@ -157,14 +157,14 @@ func Run(cmd *cobra.Command, args []string) {
157157
c := make(chan struct{})
158158
go func() {
159159
defer close(c)
160-
log.Printf("waiting for datagatherers to complete inital syncs")
160+
logs.Log.Printf("waiting for datagatherers to complete inital syncs")
161161
wg.Wait()
162162
}()
163163
select {
164164
case <-c:
165-
log.Printf("datagatherers inital sync completed")
165+
logs.Log.Printf("datagatherers inital sync completed")
166166
case <-time.After(60 * time.Second):
167-
log.Fatalf("datagatherers inital sync failed due to timeout of 60 seconds")
167+
logs.Log.Fatalf("datagatherers inital sync failed due to timeout of 60 seconds")
168168
}
169169

170170
// begin the datagathering loop, periodically sending data to the
@@ -173,7 +173,7 @@ func Run(cmd *cobra.Command, args []string) {
173173
for {
174174
// if period is set in the config, then use that if not already set
175175
if Period == 0 && config.Period > 0 {
176-
log.Printf("Using period from config %s", config.Period)
176+
logs.Log.Printf("Using period from config %s", config.Period)
177177
Period = config.Period
178178
}
179179

@@ -188,16 +188,16 @@ func Run(cmd *cobra.Command, args []string) {
188188
}
189189

190190
func getConfiguration() (Config, client.Client) {
191-
log.Printf("Preflight agent version: %s (%s)", version.PreflightVersion, version.Commit)
191+
logs.Log.Printf("Preflight agent version: %s (%s)", version.PreflightVersion, version.Commit)
192192
file, err := os.Open(ConfigFilePath)
193193
if err != nil {
194-
log.Fatalf("Failed to load config file for agent from: %s", ConfigFilePath)
194+
logs.Log.Fatalf("Failed to load config file for agent from: %s", ConfigFilePath)
195195
}
196196
defer file.Close()
197197

198198
b, err := ioutil.ReadAll(file)
199199
if err != nil {
200-
log.Fatalf("Failed to read config file: %s", err)
200+
logs.Log.Fatalf("Failed to read config file: %s", err)
201201
}
202202

203203
// If the ClientID of the service account is specified, then assume we are in Venafi Cloud mode.
@@ -207,29 +207,29 @@ func getConfiguration() (Config, client.Client) {
207207

208208
config, err := ParseConfig(b, VenafiCloudMode)
209209
if err != nil {
210-
log.Fatalf("Failed to parse config file: %s", err)
210+
logs.Log.Fatalf("Failed to parse config file: %s", err)
211211
}
212212

213213
baseURL := config.Server
214214
if baseURL == "" {
215-
log.Printf("Using deprecated Endpoint configuration. User Server instead.")
215+
logs.Log.Printf("Using deprecated Endpoint configuration. User Server instead.")
216216
baseURL = fmt.Sprintf("%s://%s", config.Endpoint.Protocol, config.Endpoint.Host)
217217
_, err = url.Parse(baseURL)
218218
if err != nil {
219-
log.Fatalf("Failed to build URL: %s", err)
219+
logs.Log.Fatalf("Failed to build URL: %s", err)
220220
}
221221
}
222222

223223
if Period == 0 && config.Period == 0 && !OneShot {
224-
log.Fatalf("Failed to load period, must be set as flag or in config")
224+
logs.Log.Fatalf("Failed to load period, must be set as flag or in config")
225225
}
226226

227227
dump, err := config.Dump()
228228
if err != nil {
229-
log.Fatalf("Failed to dump config: %s", err)
229+
logs.Log.Fatalf("Failed to dump config: %s", err)
230230
}
231231

232-
log.Printf("Loaded config: \n%s", dump)
232+
logs.Log.Printf("Loaded config: \n%s", dump)
233233

234234
var credentials client.Credentials
235235
if ClientID != "" {
@@ -240,21 +240,21 @@ func getConfiguration() (Config, client.Client) {
240240
} else if CredentialsPath != "" {
241241
file, err = os.Open(CredentialsPath)
242242
if err != nil {
243-
log.Fatalf("Failed to load credentials from file %s", CredentialsPath)
243+
logs.Log.Fatalf("Failed to load credentials from file %s", CredentialsPath)
244244
}
245245
defer file.Close()
246246

247247
b, err = io.ReadAll(file)
248248
if err != nil {
249-
log.Fatalf("Failed to read credentials file: %v", err)
249+
logs.Log.Fatalf("Failed to read credentials file: %v", err)
250250
}
251251
if VenafiCloudMode {
252252
credentials, err = client.ParseVenafiCredentials(b)
253253
} else {
254254
credentials, err = client.ParseOAuthCredentials(b)
255255
}
256256
if err != nil {
257-
log.Fatalf("Failed to parse credentials file: %s", err)
257+
logs.Log.Fatalf("Failed to parse credentials file: %s", err)
258258
}
259259
}
260260

@@ -268,15 +268,15 @@ func getConfiguration() (Config, client.Client) {
268268
case credentials != nil:
269269
preflightClient, err = createCredentialClient(credentials, config, agentMetadata, baseURL)
270270
case APIToken != "":
271-
log.Println("An API token was specified, using API token authentication.")
271+
logs.Log.Println("An API token was specified, using API token authentication.")
272272
preflightClient, err = client.NewAPITokenClient(agentMetadata, APIToken, baseURL)
273273
default:
274-
log.Println("No credentials were specified, using with no authentication.")
274+
logs.Log.Println("No credentials were specified, using with no authentication.")
275275
preflightClient, err = client.NewUnauthenticatedClient(agentMetadata, baseURL)
276276
}
277277

278278
if err != nil {
279-
log.Fatalf("failed to create client: %v", err)
279+
logs.Log.Fatalf("failed to create client: %v", err)
280280
}
281281

282282
return config, preflightClient
@@ -285,19 +285,19 @@ func getConfiguration() (Config, client.Client) {
285285
func createCredentialClient(credentials client.Credentials, config Config, agentMetadata *api.AgentMetadata, baseURL string) (client.Client, error) {
286286
switch creds := credentials.(type) {
287287
case *client.VenafiSvcAccountCredentials:
288-
log.Println("Venafi Cloud mode was specified, using Venafi Service Account authentication.")
288+
logs.Log.Println("Venafi Cloud mode was specified, using Venafi Service Account authentication.")
289289
// check if config has Venafi Cloud data, use config data if it's present
290290
uploaderID := creds.ClientID
291291
uploadPath := ""
292292
if config.VenafiCloud != nil {
293-
log.Println("Loading uploader_id and upload_path from \"venafi-cloud\" configuration.")
293+
logs.Log.Println("Loading uploader_id and upload_path from \"venafi-cloud\" configuration.")
294294
uploaderID = config.VenafiCloud.UploaderID
295295
uploadPath = config.VenafiCloud.UploadPath
296296
}
297297
return client.NewVenafiCloudClient(agentMetadata, creds, baseURL, uploaderID, uploadPath)
298298

299299
case *client.OAuthCredentials:
300-
log.Println("A credentials file was specified, using oauth authentication.")
300+
logs.Log.Println("A credentials file was specified, using oauth authentication.")
301301
return client.NewOAuthClient(agentMetadata, creds, baseURL)
302302
default:
303303
return nil, errors.New("credentials file is in unknown format")
@@ -316,14 +316,14 @@ func gatherAndOutputData(config Config, preflightClient client.Client, dataGathe
316316
}
317317

318318
if InputPath != "" {
319-
log.Printf("Reading data from local file: %s", InputPath)
319+
logs.Log.Printf("Reading data from local file: %s", InputPath)
320320
data, err := ioutil.ReadFile(InputPath)
321321
if err != nil {
322-
log.Fatalf("failed to read local data file: %s", err)
322+
logs.Log.Fatalf("failed to read local data file: %s", err)
323323
}
324324
err = json.Unmarshal(data, &readings)
325325
if err != nil {
326-
log.Fatalf("failed to unmarshal local data file: %s", err)
326+
logs.Log.Fatalf("failed to unmarshal local data file: %s", err)
327327
}
328328
} else {
329329
readings = gatherData(config, dataGatherers)
@@ -332,13 +332,13 @@ func gatherAndOutputData(config Config, preflightClient client.Client, dataGathe
332332
if OutputPath != "" {
333333
data, err := json.MarshalIndent(readings, "", " ")
334334
if err != nil {
335-
log.Fatal("failed to marshal JSON")
335+
logs.Log.Fatal("failed to marshal JSON")
336336
}
337337
err = ioutil.WriteFile(OutputPath, data, 0644)
338338
if err != nil {
339-
log.Fatalf("failed to output to local file: %s", err)
339+
logs.Log.Fatalf("failed to output to local file: %s", err)
340340
}
341-
log.Printf("Data saved to local file: %s", OutputPath)
341+
logs.Log.Printf("Data saved to local file: %s", OutputPath)
342342
} else {
343343
backOff := backoff.NewExponentialBackOff()
344344
backOff.InitialInterval = 30 * time.Second
@@ -348,10 +348,10 @@ func gatherAndOutputData(config Config, preflightClient client.Client, dataGathe
348348
return postData(config, preflightClient, readings)
349349
}
350350
err := backoff.RetryNotify(post, backOff, func(err error, t time.Duration) {
351-
log.Printf("retrying in %v after error: %s", t, err)
351+
logs.Log.Printf("retrying in %v after error: %s", t, err)
352352
})
353353
if err != nil {
354-
log.Fatalf("Exiting due to fatal error uploading: %v", err)
354+
logs.Log.Fatalf("Exiting due to fatal error uploading: %v", err)
355355
}
356356

357357
}
@@ -370,9 +370,9 @@ func gatherData(config Config, dataGatherers map[string]datagatherer.DataGathere
370370
}
371371

372372
if count >= 0 {
373-
log.Printf("successfully gathered %d items from %q datagatherer", count, k)
373+
logs.Log.Printf("successfully gathered %d items from %q datagatherer", count, k)
374374
} else {
375-
log.Printf("successfully gathered data from %q datagatherer", k)
375+
logs.Log.Printf("successfully gathered data from %q datagatherer", k)
376376
}
377377
readings = append(readings, &api.DataReading{
378378
ClusterID: config.ClusterID,
@@ -396,7 +396,7 @@ func gatherData(config Config, dataGatherers map[string]datagatherer.DataGathere
396396
}
397397

398398
if StrictMode && dgError.ErrorOrNil() != nil {
399-
log.Fatalf("halting datagathering in strict mode due to error: %s", dgError.ErrorOrNil())
399+
logs.Log.Fatalf("halting datagathering in strict mode due to error: %s", dgError.ErrorOrNil())
400400
}
401401

402402
return readings
@@ -405,7 +405,7 @@ func gatherData(config Config, dataGatherers map[string]datagatherer.DataGathere
405405
func postData(config Config, preflightClient client.Client, readings []*api.DataReading) error {
406406
baseURL := config.Server
407407

408-
log.Println("Posting data to:", baseURL)
408+
logs.Log.Println("Posting data to:", baseURL)
409409

410410
if VenafiCloudMode {
411411
// orgID and clusterID are not required for Venafi Cloud auth
@@ -416,23 +416,23 @@ func postData(config Config, preflightClient client.Client, readings []*api.Data
416416
if err != nil {
417417
return fmt.Errorf("post to server failed: %+v", err)
418418
}
419-
log.Println("Data sent successfully.")
419+
logs.Log.Println("Data sent successfully.")
420420

421421
return nil
422422
}
423423

424424
if config.OrganizationID == "" {
425425
data, err := json.Marshal(readings)
426426
if err != nil {
427-
log.Fatalf("Cannot marshal readings: %+v", err)
427+
logs.Log.Fatalf("Cannot marshal readings: %+v", err)
428428
}
429429

430430
// log and collect metrics about the upload size
431431
metric := metricPayloadSize.With(
432432
prometheus.Labels{"organization": config.OrganizationID, "cluster": config.ClusterID},
433433
)
434434
metric.Set(float64(len(data)))
435-
log.Printf("Data readings upload size: %d", len(data))
435+
logs.Log.Printf("Data readings upload size: %d", len(data))
436436
path := config.Endpoint.Path
437437
if path == "" {
438438
path = "/api/v1/datareadings"
@@ -452,7 +452,7 @@ func postData(config Config, preflightClient client.Client, readings []*api.Data
452452

453453
return fmt.Errorf("received response with status code %d. Body: [%s]", code, errorContent)
454454
}
455-
log.Println("Data sent successfully.")
455+
logs.Log.Println("Data sent successfully.")
456456
return err
457457
}
458458

@@ -464,7 +464,7 @@ func postData(config Config, preflightClient client.Client, readings []*api.Data
464464
if err != nil {
465465
return fmt.Errorf("post to server failed: %+v", err)
466466
}
467-
log.Println("Data sent successfully.")
467+
logs.Log.Println("Data sent successfully.")
468468

469469
return nil
470470
}

0 commit comments

Comments
 (0)