From e751939b68425b6aedd6bbf93704363c482880da Mon Sep 17 00:00:00 2001 From: Techassi Date: Thu, 13 Jan 2022 21:34:39 +0100 Subject: [PATCH] zapcore: Add ParseLevel (#1047) This adds the public ParseLevel function which enables the user to construct a log level based on ASCII text input. This re-uses the UnmarshalText method of Level for the heavy-lifting, but it avoids the user having to declare a local `Level` variable first. ```go var level zapcore.Level err := level.UnmarshalText([]byte("debug")) // versus level, err := zapcore.ParseLevel("debug") ``` #### Usage ```go level, err := zapcore.LevelFromString("info") // zapcore.InfoLevel, nil level, err := zapcore.LevelFromString("DEBUG") // zapcore.DebugLevel, nil level, err := zapcore.LevelFromString("FOO") // 0, "invalid level" ``` Co-authored-by: Abhinav Gupta --- zapcore/level.go | 12 ++++++++++++ zapcore/level_test.go | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/zapcore/level.go b/zapcore/level.go index e575c9f43..56e88dc0c 100644 --- a/zapcore/level.go +++ b/zapcore/level.go @@ -55,6 +55,18 @@ const ( _maxLevel = FatalLevel ) +// ParseLevel parses a level based on the lower-case or all-caps ASCII +// representation of the log level. If the provided ASCII representation is +// invalid an error is returned. +// +// This is particularly useful when dealing with text input to configure log +// levels. +func ParseLevel(text string) (Level, error) { + var level Level + err := level.UnmarshalText([]byte(text)) + return level, err +} + // String returns a lower-case ASCII representation of the log level. func (l Level) String() string { switch l { diff --git a/zapcore/level_test.go b/zapcore/level_test.go index 28b75b37f..c4a120538 100644 --- a/zapcore/level_test.go +++ b/zapcore/level_test.go @@ -76,6 +76,28 @@ func TestLevelText(t *testing.T) { } } +func TestParseLevel(t *testing.T) { + tests := []struct { + text string + level Level + err string + }{ + {"info", InfoLevel, ""}, + {"DEBUG", DebugLevel, ""}, + {"FOO", 0, `unrecognized level: "FOO"`}, + } + for _, tt := range tests { + parsedLevel, err := ParseLevel(tt.text) + if len(tt.err) == 0 { + assert.NoError(t, err) + assert.Equal(t, tt.level, parsedLevel) + } else { + assert.Error(t, err) + assert.Contains(t, err.Error(), tt.err) + } + } +} + func TestCapitalLevelsParse(t *testing.T) { tests := []struct { text string