From 84d5c3a5c727ba87d087894e77326bcdc4bde7aa Mon Sep 17 00:00:00 2001 From: Gabriel Augendre Date: Wed, 21 Jun 2023 16:56:08 +0200 Subject: [PATCH] Add GetRegisteredFields --- log.go | 11 +++++++++++ log_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/log.go b/log.go index 57909f9..e22b231 100644 --- a/log.go +++ b/log.go @@ -50,6 +50,13 @@ loop: }) } +// GetRegisteredFields returns a copy of the registered fields. +func GetRegisteredFields() []Field { + fields := make([]Field, len(registeredFields)) + copy(fields, registeredFields) + return fields +} + // CallerFrameToSkip correspond to the number of frame to skip while retrieving the caller stack var CallerFrameToSkip = 2 @@ -96,6 +103,10 @@ var ( ) func init() { + RegisterDefaultFields() +} + +func RegisterDefaultFields() { RegisterField(FieldSourceFile, FieldSourceLine, FieldCaller, FieldStackTrace) } diff --git a/log_test.go b/log_test.go index f497033..f97c661 100644 --- a/log_test.go +++ b/log_test.go @@ -19,6 +19,10 @@ const ( ) func init() { + registerDefaultFields() +} + +func registerDefaultFields() { log.RegisterField(fieldComponent, fieldAsset) } @@ -126,3 +130,37 @@ func ExampleNewStdWrapperAndSkip() { // [WARN] [asset=ExampleNewStdWrapper][caller=github.com/rockbears/log_test.ExampleNewStdWrapperAndSkip][component=rockbears/log] this is warn // [ERROR] [asset=ExampleNewStdWrapper][caller=github.com/rockbears/log_test.ExampleNewStdWrapperAndSkip][component=rockbears/log] this is error } + +func ExampleGetRegisteredFields() { + log.RegisterDefaultFields() + registerDefaultFields() + fmt.Println(log.GetRegisteredFields()) + // Output: + // [asset caller component source_file source_line stack_trace] +} + +func TestGetRegisteredFields(t *testing.T) { + log.RegisterDefaultFields() + defer log.RegisterDefaultFields() + registerDefaultFields() + defer registerDefaultFields() + + log.UnregisterField(log.GetRegisteredFields()...) + + got := log.GetRegisteredFields() + if len(got) != 0 { + t.Fatalf("want empty slice, got %s", got) + } + + log.RegisterField(log.FieldCaller) + got = log.GetRegisteredFields() + if len(got) != 1 { + t.Fatalf("want slice with length 1, got %s", got) + } + + gotField := got[0] + wantField := log.FieldCaller + if gotField != wantField { + t.Fatalf("want field %s, got %s", wantField, gotField) + } +}