From 3673c74b0f3e0901552553a359b7c669db7c53f2 Mon Sep 17 00:00:00 2001 From: Thomas Linford Date: Wed, 23 Jun 2021 16:17:13 +0200 Subject: [PATCH] Improve docs, add ExecutionIDFrom(ctx) method to Logger --- yall.go | 18 ++++++++++++++---- zaplogger/zap_logger_test.go | 9 +++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/yall.go b/yall.go index d57ed5a..36a9736 100644 --- a/yall.go +++ b/yall.go @@ -13,13 +13,20 @@ const ( MissingExecutionID = "missing_execution_id" ) +// Logger is the interface of a logger, that has methods to log with a context or without. +// With is used to decorate the logger with key-value pairs. +// ExecutionIDFrom allows to extract the execution id from the context, if present, and depends on the concrete logger +// implementation. type Logger interface { - contextLogger - noContextLogger + ContextLogger + NoContextLogger With(args ...interface{}) Logger + ExecutionIDFrom(ctx context.Context) string } -type contextLogger interface { +// ContextLogger is the interface of a logger, that has methods to log with a context. +// keysAndValues has to be formed by pairs of key and value, or single Fields. +type ContextLogger interface { Fatal(ctx context.Context, msg string, keysAndValues ...interface{}) Panic(ctx context.Context, msg string, keysAndValues ...interface{}) Error(ctx context.Context, msg string, keysAndValues ...interface{}) @@ -28,7 +35,9 @@ type contextLogger interface { Debug(ctx context.Context, msg string, keysAndValues ...interface{}) } -type noContextLogger interface { +// NoContextLogger is the interface of a logger, that has methods to log without a context. +// keysAndValues has to be formed by pairs of key and value, or single Fields. +type NoContextLogger interface { Fatalnc(msg string, keysAndValues ...interface{}) Panicnc(msg string, keysAndValues ...interface{}) Errornc(msg string, keysAndValues ...interface{}) @@ -37,6 +46,7 @@ type noContextLogger interface { Debugnc(msg string, keysAndValues ...interface{}) } +// Field is a loggable object, that can be used instead of key value pairs type Field struct { Name string Value interface{} diff --git a/zaplogger/zap_logger_test.go b/zaplogger/zap_logger_test.go index 483e076..0e2fc5f 100644 --- a/zaplogger/zap_logger_test.go +++ b/zaplogger/zap_logger_test.go @@ -79,3 +79,12 @@ func TestZapLoggerCreate(t *testing.T) { logger.Info(nil, "test") } } + +func TestExecutionIDFrom(t *testing.T) { + ctx := context.WithValue(context.Background(), yall.ExecutionIDKey, "request_id_test123") + logger, _ := zaplogger.NewLogger("test") + + executionID := logger.ExecutionIDFrom(ctx) + assert.NotEmpty(t, executionID) + assert.EqualValues(t, "request_id_test123", executionID) +}