Skip to content

Commit ae12ef7

Browse files
authored
Migrate to slog everywhere (#974)
* Migrate to `slog` everywhere Via Codex * test fixes * lint fixes * reverted status
1 parent f9cfddc commit ae12ef7

File tree

17 files changed

+161
-143
lines changed

17 files changed

+161
-143
lines changed

cmd/cirrus/main.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212
"github.com/cirruslabs/cirrus-cli/internal/opentelemetry"
1313
"github.com/cirruslabs/cirrus-cli/internal/version"
1414
"github.com/getsentry/sentry-go"
15-
"log"
15+
"log/slog"
1616
"os"
1717
"os/signal"
1818
"strings"
@@ -38,7 +38,8 @@ func main() {
3838
AttachStacktrace: true,
3939
})
4040
if err != nil {
41-
log.Fatalf("failed to initialize Sentry: %v", err)
41+
slog.Error("failed to initialize Sentry", "err", err)
42+
os.Exit(1)
4243
}
4344
defer sentry.Flush(5 * time.Second)
4445
defer sentry.Recover()

internal/agent/executor/cache.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import (
1313
"github.com/cirruslabs/cirrus-cli/internal/agent/http_cache"
1414
"github.com/cirruslabs/cirrus-cli/internal/agent/targz"
1515
"github.com/cirruslabs/cirrus-cli/pkg/api"
16-
"log"
16+
"log/slog"
1717
"net"
1818
"net/http"
1919
"net/url"
@@ -334,7 +334,7 @@ func FetchCache(
334334
) (*os.File, time.Duration, error) {
335335
cacheFile, err := os.CreateTemp(os.TempDir(), commandName)
336336
if err != nil {
337-
log.Printf("Failed to create a temp file %s: %v\n", commandName, err)
337+
slog.Error("Failed to create a temp cache file", "command", commandName, "err", err)
338338
logUploader.Write([]byte(fmt.Sprintf("\nCache miss for %s!", commandName)))
339339
return nil, 0, err
340340
}
@@ -343,30 +343,30 @@ func FetchCache(
343343
downloadStartTime := time.Now()
344344
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://%s/%s", cacheHost, cacheKey), nil)
345345
if err != nil {
346-
log.Printf("Failed to create a cache request for %s: %v\n", commandName, err)
346+
slog.Error("Failed to create a cache request", "command", commandName, "err", err)
347347
return nil, 0, err
348348
}
349349
resp, err := httpClient.Do(req)
350350
if err != nil {
351-
log.Printf("HTTP cache request for %s failed: %v\n", commandName, err)
351+
slog.Error("HTTP cache request failed", "command", commandName, "err", err)
352352
return nil, 0, err
353353
}
354354
defer resp.Body.Close()
355355

356356
if resp.StatusCode != http.StatusOK {
357-
log.Printf("HTTP cache request for %s status: %s\n", commandName, resp.Status)
357+
slog.Warn("Unexpected HTTP cache response status", "command", commandName, "status", resp.Status)
358358
return nil, 0, nil
359359
}
360360

361361
bufferedFileWriter := bufio.NewWriter(cacheFile)
362362
bytesDownloaded, err := bufferedFileWriter.ReadFrom(bufio.NewReader(resp.Body))
363363
if err != nil {
364-
log.Printf("Failed to finish downloading %s cache: %v\n", commandName, err)
364+
slog.Error("Failed to finish downloading cache", "command", commandName, "err", err)
365365
return nil, 0, err
366366
}
367367
err = bufferedFileWriter.Flush()
368368
if err != nil {
369-
log.Printf("Failed to flush %s cache: %v\n", commandName, err)
369+
slog.Error("Failed to flush cache", "command", commandName, "err", err)
370370
return nil, 0, err
371371
}
372372
downloadDuration := time.Since(downloadStartTime)

internal/agent/executor/executor.go

Lines changed: 40 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import (
44
"context"
55
"errors"
66
"fmt"
7-
"log"
7+
"log/slog"
88
"os"
99
"os/exec"
1010
"path/filepath"
@@ -91,7 +91,7 @@ func (executor *Executor) RunBuild(ctx context.Context) {
9191
defer metricsCancel()
9292
metricsResultChan := metrics.Run(metricsCtx, nil)
9393

94-
log.Println("Getting initial commands...")
94+
slog.Info("Getting initial commands...")
9595

9696
var response *api.CommandsResponse
9797
var err error
@@ -108,7 +108,7 @@ func (executor *Executor) RunBuild(ctx context.Context) {
108108
return err
109109
}, retry.OnRetry(func(n uint, err error) {
110110
numRetries++
111-
log.Printf("Failed to get initial commands: %v", err)
111+
slog.Warn("Failed to get initial commands", "err", err)
112112
}),
113113
retry.Delay(5*time.Second),
114114
retry.Attempts(0), retry.LastErrorOnly(true),
@@ -120,8 +120,8 @@ func (executor *Executor) RunBuild(ctx context.Context) {
120120
}
121121

122122
if response.ServerToken != executor.serverToken {
123-
log.Panic("Server token is incorrect!")
124-
return
123+
slog.Error("Server token is incorrect!")
124+
panic("Server token is incorrect!")
125125
}
126126

127127
// Retrieve the script/commands environment, but do not merge it into the
@@ -141,7 +141,7 @@ func (executor *Executor) RunBuild(ctx context.Context) {
141141
// "PASSWORD: VAULT[$PATH $ARGS]" would work.
142142
vaultUnboxerEnv := environment.New(scriptEnvironment)
143143

144-
log.Println("Unboxing VAULT[...] environment variables, if any")
144+
slog.Info("Unboxing VAULT[...] environment variables, if any")
145145

146146
var vaultUnboxer *vaultunboxer.VaultUnboxer
147147

@@ -153,31 +153,31 @@ func (executor *Executor) RunBuild(ctx context.Context) {
153153
}
154154

155155
message := fmt.Sprintf("failed to parse a Vault-boxed value %s: %v", value, err)
156-
log.Println(message)
156+
slog.Error(message)
157157
executor.reportError(message)
158158

159159
return
160160
}
161161

162162
if vaultUnboxer == nil {
163-
log.Println("Found at least one VAULT[...] environment variable, initializing Vault client")
163+
slog.Info("Found at least one VAULT[...] environment variable, initializing Vault client")
164164

165165
vaultUnboxer, err = vaultunboxer.NewFromEnvironment(ctx, vaultUnboxerEnv)
166166
if err != nil {
167167
message := fmt.Sprintf("failed to initialize a Vault client: %v", err)
168-
log.Println(message)
168+
slog.Error(message)
169169
executor.reportError(message)
170170

171171
return
172172
}
173173

174-
log.Println("Vault client successfully initialized")
174+
slog.Info("Vault client successfully initialized")
175175
}
176176

177177
unboxedValue, err := vaultUnboxer.Unbox(ctx, boxedValue)
178178
if err != nil {
179179
message := fmt.Sprintf("failed to unbox a Vault-boxed value %s: %v", value, err)
180-
log.Println(message)
180+
slog.Error(message)
181181
executor.reportError(message)
182182

183183
return
@@ -191,19 +191,19 @@ func (executor *Executor) RunBuild(ctx context.Context) {
191191

192192
workingDir, ok := executor.env.Lookup("CIRRUS_WORKING_DIR")
193193
if ok {
194-
log.Printf("Changing current working directory to %s", workingDir)
194+
slog.Info("Changing current working directory", "path", workingDir)
195195

196196
EnsureFolderExists(workingDir)
197197

198198
if err := os.Chdir(workingDir); err != nil {
199199
message := fmt.Sprintf("Failed to change current working directory to '%s': %v", workingDir, err)
200-
log.Println(message)
200+
slog.Error(message)
201201
executor.reportError(message)
202202

203203
return
204204
}
205205
} else {
206-
log.Printf("Not changing current working directory because CIRRUS_WORKING_DIR is not set")
206+
slog.Info("Not changing current working directory because CIRRUS_WORKING_DIR is not set")
207207
}
208208

209209
commands := response.Commands
@@ -240,7 +240,7 @@ func (executor *Executor) RunBuild(ctx context.Context) {
240240
executor.env.AddSensitiveValues(response.SecretsToMask...)
241241

242242
if len(commands) == 0 {
243-
log.Printf("No commands to run, exiting!")
243+
slog.Info("No commands to run, exiting!")
244244

245245
return
246246
}
@@ -299,7 +299,7 @@ func (executor *Executor) RunBuild(ctx context.Context) {
299299
})
300300
ub.Flush(ctx, executor.taskIdentification())
301301

302-
log.Printf("Executing %s...", command.Name)
302+
slog.Info("Executing command", "name", command.Name)
303303

304304
var stepCtx context.Context
305305

@@ -330,7 +330,7 @@ func (executor *Executor) RunBuild(ctx context.Context) {
330330
currentCommandStatus = api.Status_FAILED
331331
}
332332

333-
log.Printf("%s %s!", command.Name, strings.ToLower(currentCommandStatus.String()))
333+
slog.Info("Command finished", "name", command.Name, "status", strings.ToLower(currentCommandStatus.String()))
334334

335335
ub.Queue(&api.CommandResult{
336336
Name: command.Name,
@@ -342,10 +342,10 @@ func (executor *Executor) RunBuild(ctx context.Context) {
342342

343343
ub.Flush(ctx, executor.taskIdentification())
344344

345-
log.Printf("Background commands to clean up after: %d!\n", len(executor.backgroundCommands))
345+
slog.Info("Background commands to clean up after", "count", len(executor.backgroundCommands))
346346
for i := 0; i < len(executor.backgroundCommands); i++ {
347347
backgroundCommand := executor.backgroundCommands[i]
348-
log.Printf("Cleaning up after background command %s...\n", backgroundCommand.Name)
348+
slog.Info("Cleaning up after background command", "name", backgroundCommand.Name)
349349
err := backgroundCommand.Cmd.Process.Kill()
350350
if err != nil {
351351
backgroundCommand.Logs.Write([]byte(fmt.Sprintf("\nFailed to stop background script %s: %s!", backgroundCommand.Name, err)))
@@ -354,7 +354,7 @@ func (executor *Executor) RunBuild(ctx context.Context) {
354354
}
355355

356356
// Retrieve resource utilization metrics
357-
log.Println("Retrieving resource utilization metrics...")
357+
slog.Info("Retrieving resource utilization metrics...")
358358

359359
metricsCancel()
360360

@@ -363,15 +363,16 @@ func (executor *Executor) RunBuild(ctx context.Context) {
363363
select {
364364
case metricsResult := <-metricsResultChan:
365365
if resourceUtilization := metricsResult.ResourceUtilization; resourceUtilization != nil {
366-
log.Printf("Received metrics: %d CPU points, %d memory points and %d errors\n",
367-
len(metricsResult.ResourceUtilization.CpuChart), len(metricsResult.ResourceUtilization.MemoryChart),
368-
len(metricsResult.Errors()))
366+
slog.Info("Received metrics",
367+
"cpu_points", len(metricsResult.ResourceUtilization.CpuChart),
368+
"memory_points", len(metricsResult.ResourceUtilization.MemoryChart),
369+
"errors", len(metricsResult.Errors()))
369370
} else {
370-
log.Println("Received no metrics (this OS/architecture likely doesn't support metric gathering)")
371+
slog.Info("Received no metrics (this OS/architecture likely doesn't support metric gathering)")
371372
}
372373
for _, err := range metricsResult.Errors() {
373374
message := fmt.Sprintf("Encountered an error while gathering resource utilization metrics: %v", err)
374-
log.Println(message)
375+
slog.Warn(message)
375376
_, _ = client.CirrusClient.ReportAgentWarning(ctx, &api.ReportAgentProblemRequest{
376377
TaskIdentification: executor.taskIdentification(),
377378
Message: message,
@@ -384,7 +385,7 @@ func (executor *Executor) RunBuild(ctx context.Context) {
384385
//
385386
// [1]: https://github.com/shirou/gopsutil/issues/724
386387
message := "Failed to retrieve resource utilization metrics in time"
387-
log.Println(message)
388+
slog.Warn(message)
388389
_, _ = client.CirrusClient.ReportAgentWarning(ctx, &api.ReportAgentProblemRequest{
389390
TaskIdentification: executor.taskIdentification(),
390391
Message: message,
@@ -404,7 +405,7 @@ func (executor *Executor) RunBuild(ctx context.Context) {
404405
})
405406
}
406407

407-
log.Println("Reporting that the agent has finished...")
408+
slog.Info("Reporting that the agent has finished...")
408409

409410
if err = retry.Do(
410411
func() error {
@@ -417,13 +418,13 @@ func (executor *Executor) RunBuild(ctx context.Context) {
417418
})
418419
return err
419420
}, retry.OnRetry(func(n uint, err error) {
420-
log.Printf("Failed to report that the agent has finished: %v\nRetrying...\n", err)
421+
slog.Warn("Failed to report that the agent has finished, retrying...", "err", err)
421422
}),
422423
retry.Delay(10*time.Second),
423424
retry.Attempts(2),
424425
retry.Context(context.WithoutCancel(ctx)),
425426
); err != nil {
426-
log.Printf("Failed to report that the agent has finished: %v\n", err)
427+
slog.Error("Failed to report that the agent has finished", "err", err)
427428
}
428429
}
429430

@@ -507,7 +508,7 @@ func (executor *Executor) performStep(ctx context.Context, currentStep *api.Comm
507508
cirrusEnv, err := cirrusenv.New(executor.taskId)
508509
if err != nil {
509510
message := fmt.Sprintf("Failed initialize CIRRUS_ENV subsystem: %v", err)
510-
log.Print(message)
511+
slog.Error(message)
511512
fmt.Fprintln(logUploader, message)
512513
return &StepResult{
513514
Success: false,
@@ -545,10 +546,13 @@ func (executor *Executor) performStep(ctx context.Context, currentStep *api.Comm
545546
Cmd: cmd,
546547
Logs: logUploader,
547548
})
548-
log.Printf("Started execution of #%d background command %s\n", len(executor.backgroundCommands), currentStep.Name)
549+
slog.Info("Started execution of background command",
550+
"index", len(executor.backgroundCommands),
551+
"name", currentStep.Name)
549552
success = true
550553
} else {
551-
log.Printf("Failed to create command line for background command %s: %s\n", currentStep.Name, err)
554+
slog.Error("Failed to create command line for background command",
555+
"name", currentStep.Name, "err", err)
552556
_, _ = logUploader.Write([]byte(fmt.Sprintf("Failed to create command line: %s", err)))
553557
logUploader.Finalize()
554558
success = false
@@ -569,22 +573,22 @@ func (executor *Executor) performStep(ctx context.Context, currentStep *api.Comm
569573
for {
570574
switch operation := (<-operationChan).(type) {
571575
case *terminalwrapper.LogOperation:
572-
log.Println(operation.Message)
576+
slog.Info(operation.Message)
573577
_, _ = fmt.Fprintln(logUploader, operation.Message)
574578
case *terminalwrapper.ExitOperation:
575579
success = operation.Success
576580
break WaitForTerminalInstructionFor
577581
}
578582
}
579583
default:
580-
log.Printf("Unsupported instruction %T", instruction)
584+
slog.Warn("Unsupported instruction", "type", fmt.Sprintf("%T", instruction))
581585
success = false
582586
}
583587

584588
cirrusEnvVariables, err := cirrusEnv.Consume()
585589
if err != nil {
586590
message := fmt.Sprintf("Failed collect CIRRUS_ENV subsystem results: %v", err)
587-
log.Print(message)
591+
slog.Error(message)
588592
fmt.Fprintln(logUploader, message)
589593
}
590594

@@ -656,7 +660,7 @@ func (executor *Executor) CreateFile(
656660
case *api.FileInstruction_FromContents:
657661
content = source.FromContents
658662
default:
659-
log.Printf("Unsupported source %T", source)
663+
slog.Warn("Unsupported source", "type", fmt.Sprintf("%T", source))
660664

661665
return false
662666
}

0 commit comments

Comments
 (0)