From 89fb20bb5af80320ff1a31f4f5b85cda9174a0f6 Mon Sep 17 00:00:00 2001 From: hfuss Date: Tue, 14 May 2024 12:27:30 -0400 Subject: [PATCH 1/2] [log] WithLogFields for Configuring Larger Logging Contexts Signed-off-by: hfuss --- pkg/log/log.go | 18 ++++++++++++++++++ pkg/log/log_test.go | 6 ++++++ 2 files changed, 24 insertions(+) diff --git a/pkg/log/log.go b/pkg/log/log.go index 9c7c7c3d..afa4a9a8 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -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..82e77bef 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -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") +} From 47662315aa8f8d6c27cb48fb02cd23512e37c630 Mon Sep 17 00:00:00 2001 From: hfuss Date: Tue, 14 May 2024 12:34:11 -0400 Subject: [PATCH 2/2] fix lint Signed-off-by: hfuss --- pkg/log/log.go | 2 +- pkg/log/log_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/log/log.go b/pkg/log/log.go index afa4a9a8..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 // diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index 82e77bef..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 //