Skip to content

Commit

Permalink
feat: log/slogutil: add AttrsFromAny(), LogOrNotAny()
Browse files Browse the repository at this point in the history
  • Loading branch information
grokify committed Sep 8, 2024
1 parent 09bfdd0 commit 5651b53
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions log/slogutil/slogutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package slogutil

import (
"context"
"fmt"
"log/slog"
)

Expand All @@ -13,3 +14,24 @@ func LogOrNot(ctx context.Context, logger *slog.Logger, level slog.Level, msg st
}
logger.LogAttrs(ctx, level, msg, attrs...)
}

func LogOrNotAny(ctx context.Context, logger *slog.Logger, level slog.Level, msg string, args ...any) {
attrs := AttrsFromAny(args...)
LogOrNot(ctx, logger, level, msg, attrs...)
}

func AttrsFromAny(args ...any) []slog.Attr {
var attrs []slog.Attr
for i := 0; i < len(args); i += 2 {
key, ok := args[i].(string)
if !ok {
key = fmt.Sprintf("%v", key)
}
if i < len(args)-1 {
attrs = append(attrs, slog.Any(key, args[i+1]))
} else {
attrs = append(attrs, slog.Any(key, nil))
}
}
return attrs
}

0 comments on commit 5651b53

Please sign in to comment.