Skip to content

Commit

Permalink
feat: add cloudslog.Errors
Browse files Browse the repository at this point in the history
  • Loading branch information
hugosandelius committed Nov 20, 2024
1 parent d359901 commit 84e9ad3
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
24 changes: 24 additions & 0 deletions cloudslog/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package cloudslog

import (
"encoding/json"
"log/slog"
)

// Errors creates a slog attribute for a list of errors.
// unlike slog.Any, this will render the error strings when using slog.JSONHandler.
func Errors(errors []error) slog.Attr {
jsonErrors := make([]error, len(errors))
for i, err := range errors {
jsonErrors[i] = &jsonError{error: err}
}
return slog.Any("errors", jsonErrors)
}

type jsonError struct {
error
}

func (j jsonError) MarshalJSON() ([]byte, error) {
return json.Marshal(j.error.Error())
}
20 changes: 20 additions & 0 deletions cloudslog/errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package cloudslog

import (
"errors"
"log/slog"
"strings"
"testing"

"gotest.tools/v3/assert"
)

func TestErrors(t *testing.T) {
t.Run("errors", func(t *testing.T) {
var b strings.Builder
logger := slog.New(newHandler(&b, LoggerConfig{}))

logger.Info("test", Errors([]error{errors.New("test_error")}))
assert.Assert(t, strings.Contains(b.String(), "test_error"))
})
}

0 comments on commit 84e9ad3

Please sign in to comment.