Skip to content

Commit

Permalink
Add GetRegisteredFields
Browse files Browse the repository at this point in the history
  • Loading branch information
Crocmagnon authored and fsamin committed Jun 21, 2023
1 parent 750b638 commit 84d5c3a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
11 changes: 11 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -96,6 +103,10 @@ var (
)

func init() {
RegisterDefaultFields()
}

func RegisterDefaultFields() {
RegisterField(FieldSourceFile, FieldSourceLine, FieldCaller, FieldStackTrace)
}

Expand Down
38 changes: 38 additions & 0 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ const (
)

func init() {
registerDefaultFields()
}

func registerDefaultFields() {
log.RegisterField(fieldComponent, fieldAsset)
}

Expand Down Expand Up @@ -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)
}
}

0 comments on commit 84d5c3a

Please sign in to comment.