Skip to content
This repository has been archived by the owner on Oct 14, 2024. It is now read-only.

Commit

Permalink
fix: return level.go
Browse files Browse the repository at this point in the history
Signed-off-by: Musilah <[email protected]>
  • Loading branch information
Musilah committed Jan 12, 2024
1 parent cda31a1 commit 077c0f1
Show file tree
Hide file tree
Showing 2 changed files with 111 additions and 0 deletions.
23 changes: 23 additions & 0 deletions logger/level.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0

package logger

import (
"errors"
"log/slog"
)

// ErrInvalidLogLevel indicates an unrecognized log level.
var ErrInvalidLogLevel = errors.New("unrecognized log level")

// UnmarshalText is a helper function to convert text to slog's Level type.
func UnmarshalText(text string) (slog.Level, error) {
var level slog.Level

err := level.UnmarshalText([]byte(text))
if err != nil {
return 0, ErrInvalidLogLevel
}
return level, nil
}
88 changes: 88 additions & 0 deletions logger/level_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0

package logger

import (
"fmt"
"log/slog"
"testing"

"github.com/stretchr/testify/assert"
)

func TestUnmarshalText(t *testing.T) {
cases := []struct {
desc string
input string
output slog.Level
err error
}{
{
desc: "select log level Not_A_Level",
input: "Not_A_Level",
output: 0,
err: ErrInvalidLogLevel,
},
{
desc: "select log level Bad_Input",
input: "Bad_Input",
output: 0,
err: ErrInvalidLogLevel,
},
{
desc: "select log level debug",
input: "debug",
output: slog.LevelDebug,
err: nil,
},
{
desc: "select log level DEBUG",
input: "DEBUG",
output: slog.LevelDebug,
err: nil,
},
{
desc: "select log level info",
input: "info",
output: slog.LevelInfo,
err: nil,
},
{
desc: "select log level INFO",
input: "INFO",
output: slog.LevelInfo,
err: nil,
},
{
desc: "select log level warn",
input: "warn",
output: slog.LevelWarn,
err: nil,
},
{
desc: "select log level WARN",
input: "WARN",
output: slog.LevelWarn,
err: nil,
},
{
desc: "select log level Error",
input: "Error",
output: slog.LevelError,
err: nil,
},
{
desc: "select log level ERROR",
input: "ERROR",
output: slog.LevelError,
err: nil,
},
}

for _, tc := range cases {
level, err := UnmarshalText(tc.input)
assert.Equal(t, tc.output, level, fmt.Sprintf("%s: expected %s got %v", tc.desc, tc.output, level))
assert.Equal(t, tc.err, err, fmt.Sprintf("%s: expected %v got %v", tc.desc, tc.err, err))
}
}

0 comments on commit 077c0f1

Please sign in to comment.