Log os.Args, bricks version, and exit status (#324)

## Changes
<!-- Summary of your changes that are easy to understand -->
1. Log os.Args and bricks version before every command execution
2. After a command execution, logs the error and exit code

## Tests
<!-- How is this tested? -->
Manually, 

case 1: Run `bricks version` successfully
```
shreyas.goenka@THW32HFW6T bricks % bricks version --log-level=info --log-file stderr
time=2023-04-12T00:15:04.011+02:00 level=INFO source=root.go:34 msg="process args: [bricks, version, --log-level=info, --log-file, stderr]"
time=2023-04-12T00:15:04.011+02:00 level=INFO source=root.go:35 msg="version: 0.0.0-dev+375eb1c50283"
0.0.0-dev+375eb1c50283
time=2023-04-12T00:15:04.011+02:00 level=INFO source=root.go:68 msg="exit code: 0"
```

case 2: Run `bricks bundle deploy` in a working dir where `bundle.yml`
does not exist
```
shreyas.goenka@THW32HFW6T bricks % bricks bundle deploy --log-level=info --log-file=stderr
time=2023-04-12T00:19:16.783+02:00 level=INFO source=root.go:34 msg="process args: [bricks, bundle, deploy, --log-level=info, --log-file=stderr]"
time=2023-04-12T00:19:16.784+02:00 level=INFO source=root.go:35 msg="version: 0.0.0-dev+375eb1c50283"
Error: unable to locate bundle root: bundle.yml not found
time=2023-04-12T00:19:16.784+02:00 level=ERROR source=root.go:64 msg="unable to locate bundle root: bundle.yml not found"
time=2023-04-12T00:19:16.784+02:00 level=ERROR source=root.go:65 msg="exit code: 1"
```
This commit is contained in:
shreyas-goenka 2023-04-12 22:12:36 +02:00 committed by GitHub
parent 417839021b
commit 1fc903943d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 27 additions and 1 deletions

View File

@ -4,8 +4,12 @@ import (
"context"
"fmt"
"os"
"strings"
"github.com/databricks/bricks/internal/build"
"github.com/databricks/bricks/libs/log"
"github.com/spf13/cobra"
"golang.org/x/exp/slog"
)
// RootCmd represents the base command when called without any subcommands
@ -29,6 +33,11 @@ var RootCmd = &cobra.Command{
return err
}
logger := log.GetLogger(ctx)
logger.Info("start",
slog.String("version", build.GetInfo().Version),
slog.String("args", strings.Join(os.Args, ", ")))
// Configure progress logger
ctx, err = initializeProgressLogger(ctx)
if err != nil {
@ -53,7 +62,24 @@ func flagErrorFunc(c *cobra.Command, err error) error {
func Execute() {
// TODO: deferred panic recovery
ctx := context.Background()
err := RootCmd.ExecuteContext(ctx)
// Run the command
cmd, err := RootCmd.ExecuteContextC(ctx)
// Log exit status and error
// We only log if logger initialization succeeded and is stored in command
// context
if logger, ok := log.FromContext(cmd.Context()); ok {
if err == nil {
logger.Info("completed execution",
slog.String("exit_code", "0"))
} else {
logger.Error("failed execution",
slog.String("exit_code", "1"),
slog.String("error", err.Error()))
}
}
if err != nil {
os.Exit(1)
}