Skip to content

Commit

Permalink
TextUnmarshaler for Options for env
Browse files Browse the repository at this point in the history
By implementing the encoding.TextUnmarshaler, Options can be populated
by environment variables from env.
  • Loading branch information
oxzi authored and lippserd committed Oct 8, 2024
1 parent 1c61013 commit f22ad52
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
27 changes: 27 additions & 0 deletions logging/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,39 @@ import (
"github.com/pkg/errors"
"go.uber.org/zap/zapcore"
"os"
"strings"
"time"
)

// Options define child loggers with their desired log level.
type Options map[string]zapcore.Level

// UnmarshalText implements encoding.TextUnmarshaler to allow Options to be parsed by env.
//
// This custom TextUnmarshaler is necessary as - for the moment - env does not support map[T]encoding.TextUnmarshaler.
// After <https://github.com/caarlos0/env/pull/323> got merged and a new env release was drafted, this method can be
// removed.
func (o *Options) UnmarshalText(text []byte) error {
optionsMap := make(map[string]zapcore.Level)

for _, entry := range strings.Split(string(text), ",") {
key, valueStr, found := strings.Cut(entry, ":")
if !found {
return fmt.Errorf("entry %q cannot be unmarshalled as an Option entry", entry)
}

valueLvl, err := zapcore.ParseLevel(valueStr)
if err != nil {
return fmt.Errorf("entry %q cannot be unmarshalled as level, %w", entry, err)
}

optionsMap[key] = valueLvl
}

*o = optionsMap
return nil
}

// Config defines Logger configuration.
type Config struct {
// zapcore.Level at 0 is for info level.
Expand Down
14 changes: 3 additions & 11 deletions logging/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,9 @@ func TestConfig(t *testing.T) {
},
},
{
name: "options-as-ints",
opts: config.EnvOptions{Environment: map[string]string{"OPTIONS": "foo:-1,bar:0,buz:4"}},
expected: Config{
Output: "console",
Interval: 20 * time.Second,
Options: map[string]zapcore.Level{
"foo": zapcore.DebugLevel,
"bar": zapcore.InfoLevel,
"buz": zapcore.PanicLevel,
},
},
name: "options-invalid-levels",
opts: config.EnvOptions{Environment: map[string]string{"OPTIONS": "foo:foo,bar:0"}},
error: true,
},
}

Expand Down

0 comments on commit f22ad52

Please sign in to comment.