diff --git a/pkg/log/log.go b/pkg/log/log.go index 9c7c7c3d..a7f70bc8 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -1,4 +1,4 @@ -// Copyright © 2022 Kaleido, Inc. +// Copyright © 2024 Kaleido, Inc. // // SPDX-License-Identifier: Apache-2.0 // @@ -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 { + 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{}) diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index 2bb66e3f..14c9aa76 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -1,4 +1,4 @@ -// Copyright © 2022 Kaleido, Inc. +// Copyright © 2024 Kaleido, Inc. // // SPDX-License-Identifier: Apache-2.0 // @@ -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") +}