fixed and normalized logs error serialization

This commit is contained in:
Gani Georgiev
2025-03-23 21:17:51 +02:00
parent f99903792a
commit 3f14a6eab7
35 changed files with 151 additions and 51 deletions
+69 -7
View File
@@ -2,9 +2,12 @@ package logger
import (
"context"
"encoding/json"
"errors"
"log/slog"
"sync"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/pocketbase/pocketbase/tools/types"
)
@@ -251,14 +254,73 @@ func (h *BatchHandler) resolveAttr(data map[string]any, attr slog.Attr) error {
data[attr.Key] = groupData
}
default:
v := attr.Value.Any()
if err, ok := v.(error); ok {
data[attr.Key] = err.Error()
} else {
data[attr.Key] = v
}
data[attr.Key] = normalizeLogAttrValue(attr.Value.Any())
}
return nil
}
func normalizeLogAttrValue(rawAttrValue any) any {
switch attrV := rawAttrValue.(type) {
case validation.Errors:
out := make(map[string]any, len(attrV))
for k, v := range attrV {
out[k] = serializeLogError(v)
}
return out
case map[string]validation.Error:
out := make(map[string]any, len(attrV))
for k, v := range attrV {
out[k] = serializeLogError(v)
}
return out
case map[string]error:
out := make(map[string]any, len(attrV))
for k, v := range attrV {
out[k] = serializeLogError(v)
}
return out
case map[string]any:
out := make(map[string]any, len(attrV))
for k, v := range attrV {
switch vv := v.(type) {
case error:
out[k] = serializeLogError(vv)
default:
out[k] = normalizeLogAttrValue(vv)
}
}
return out
case error:
// check for wrapped validation.Errors
var ve validation.Errors
if errors.As(attrV, &ve) {
out := make(map[string]any, len(ve))
for k, v := range ve {
out[k] = serializeLogError(v)
}
return map[string]any{
"data": out,
"raw": serializeLogError(attrV),
}
}
return serializeLogError(attrV)
default:
return attrV
}
}
func serializeLogError(err error) any {
if err == nil {
return nil
}
// prioritize a json structured format (e.g. validation.Errors)
jsonErr, ok := err.(json.Marshaler)
if ok {
return jsonErr
}
// fallback to its original string representation
return err.Error()
}