Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion pkg/log/log.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2022 Kaleido, Inc.
// Copyright © 2024 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
Expand Down Expand Up @@ -48,6 +48,24 @@ func WithLogField(ctx context.Context, key, value string) context.Context {
return WithLogger(ctx, loggerFromContext(ctx).WithField(key, value))
}

func WithLogFields(ctx context.Context, keyValues ...string) context.Context {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having ...string is fine to be consistent with WithLogField but it doesn't stop us having logrus.Fields one

if len(keyValues)%2 != 0 {
panic("odd number of key-value entry fields provided, cannot determine key-value pairs")
}

entry := loggerFromContext(ctx)
fields := logrus.Fields{}
for i := 0; i < len(keyValues); i += 2 {
key := keyValues[i]
value := keyValues[i+1]
if len(value) > 61 {
value = value[0:61] + "..."
}
fields[key] = value
}
return WithLogger(ctx, entry.WithFields(fields))
}

// LoggerFromContext returns the logger for the current context, or no logger if there is no context
func loggerFromContext(ctx context.Context) *logrus.Entry {
logger := ctx.Value(ctxLogKey{})
Expand Down
8 changes: 7 additions & 1 deletion pkg/log/log_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2022 Kaleido, Inc.
// Copyright © 2024 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
Expand Down Expand Up @@ -82,3 +82,9 @@ func TestSetFormattingJSONEnabled(t *testing.T) {

L(context.Background()).Infof("JSON logs")
}

func TestLogWithFields(t *testing.T) {
l := WithLogFields(context.Background(), "func", "test", "component", "tester")

L(l).Infof("logging with several fields")
}