Use cmdio logger to log bricks cmd execution errors (#348)

## Changes
Uses the cmdio logger to log the execution error

## Tests
Manually by making the root command return fake errors. Here is the
output:
```
shreyas.goenka@THW32HFW6T bricks % bricks bundle validate
Error: my foo error
```

```
shreyas.goenka@THW32HFW6T bricks % bricks bundle validate --progress-format=json
{
  "error": "my foo error"
}
```

---------

Co-authored-by: Pieter Noordhuis <pieter.noordhuis@databricks.com>
This commit is contained in:
shreyas-goenka 2023-04-24 12:11:52 +02:00 committed by GitHub
parent cd1486906d
commit 43bc9a0d9d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 0 deletions

View File

@ -7,6 +7,7 @@ import (
"strings"
"github.com/databricks/bricks/internal/build"
"github.com/databricks/bricks/libs/cmdio"
"github.com/databricks/bricks/libs/log"
"github.com/spf13/cobra"
"golang.org/x/exp/slog"
@ -23,6 +24,9 @@ var RootCmd = &cobra.Command{
// The usage string is include in [flagErrorFunc] for flag errors only.
SilenceUsage: true,
// Silence error printing by cobra. Errors are printed through cmdio.
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
@ -64,6 +68,11 @@ func Execute() {
// Run the command
cmd, err := RootCmd.ExecuteContextC(ctx)
if err != nil {
// If cmdio logger initialization succeeds, then this function logs with the
// initialized cmdio logger, otherwise with the default cmdio logger
cmdio.LogError(cmd.Context(), err)
}
// Log exit status and error
// We only log if logger initialization succeeded and is stored in command

15
libs/cmdio/error_event.go Normal file
View File

@ -0,0 +1,15 @@
package cmdio
import "fmt"
type ErrorEvent struct {
Error string `json:"error"`
}
func (event *ErrorEvent) String() string {
return fmt.Sprintf("Error: %s", event.Error)
}
func (event *ErrorEvent) IsInplaceSupported() bool {
return false
}

View File

@ -64,6 +64,16 @@ func LogString(ctx context.Context, message string) {
})
}
func LogError(ctx context.Context, err error) {
logger, ok := FromContext(ctx)
if !ok {
logger = Default()
}
logger.Log(&ErrorEvent{
Error: err.Error(),
})
}
func Ask(ctx context.Context, question string) (bool, error) {
logger, ok := FromContext(ctx)
if !ok {