-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d359901
commit 84e9ad3
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")) | ||
}) | ||
} |