From 619401cf4952308bec79a2c37f174eb0818b19d9 Mon Sep 17 00:00:00 2001 From: Hugo Sandelius Date: Wed, 20 Nov 2024 13:43:18 +0100 Subject: [PATCH] feat: add cloudslog.Errors --- cloudslog/errors.go | 28 ++++++++++++++++++++++++++++ cloudslog/errors_test.go | 20 ++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 cloudslog/errors.go create mode 100644 cloudslog/errors_test.go diff --git a/cloudslog/errors.go b/cloudslog/errors.go new file mode 100644 index 0000000..0d4da1f --- /dev/null +++ b/cloudslog/errors.go @@ -0,0 +1,28 @@ +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{err: err} + } + return slog.Any("errors", jsonErrors) +} + +type jsonError struct { + err error +} + +func (j jsonError) MarshalJSON() ([]byte, error) { + return json.Marshal(j.err.Error()) +} + +func (j jsonError) Error() string { + return j.err.Error() +} diff --git a/cloudslog/errors_test.go b/cloudslog/errors_test.go new file mode 100644 index 0000000..d525423 --- /dev/null +++ b/cloudslog/errors_test.go @@ -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")) + }) +}