Skip to content

Commit

Permalink
LogEntrySetFields: Use the varargs syntax to supply the additional lo…
Browse files Browse the repository at this point in the history
…g arguments correctly

Without the change in this changeset, running `go test` fails with:

```
./httplog.go:361:37: slog.Logger.With arg "attrs" should be a string or a slog.Attr (possible missing key or value)
FAIL
```

This is due to the fact that the array of `slog.Attr`s was supplied as
a single arg (i.e. a single slice of attributes) to
`*entry.Logger.With`, instead of a variable number of arguments.

Example:

```go
fields := map[string]any{
        "remote": "example.com",
        "action": "update",
}
httplog.LogEntrySetFields(ctx, fields)
```

Without this change, the updated example that uses LogEntrySetFields
creates the following log entry:

```
user: "user1" !BADKEY: [remote=example.com action=update]
```

With the change the log line for the updated example is:

```
user: "user1" remote: "example.com" action: "update"
```
  • Loading branch information
stefansaasen committed Feb 13, 2024
1 parent 843b227 commit 4e4e664
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions httplog.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,12 +352,12 @@ func LogEntrySetField(ctx context.Context, key string, value slog.Value) {

func LogEntrySetFields(ctx context.Context, fields map[string]interface{}) {
if entry, ok := ctx.Value(middleware.LogEntryCtxKey).(*RequestLoggerEntry); ok {
attrs := make([]slog.Attr, len(fields))
attrs := make([]any, len(fields))
i := 0
for k, v := range fields {
attrs[i] = slog.Attr{Key: k, Value: slog.AnyValue(v)}
i++
}
entry.Logger = *entry.Logger.With(attrs)
entry.Logger = *entry.Logger.With(attrs...)
}
}

0 comments on commit 4e4e664

Please sign in to comment.