Skip to content

Commit

Permalink
Add logging when optional file is not found
Browse files Browse the repository at this point in the history
  • Loading branch information
Yasss committed Aug 22, 2019
1 parent 51fcea2 commit a3c6fcb
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
5 changes: 3 additions & 2 deletions backend/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import (
"gopkg.in/yaml.v2"
)

type ErrOpenOptionalFile error

// Backend that loads a configuration from a file.
// It supports json and yaml formats.
type Backend struct {
Expand Down Expand Up @@ -42,8 +44,7 @@ func (b *Backend) Unmarshal(ctx context.Context, to interface{}) error {
f, err := os.Open(b.path)
if err != nil {
if b.optional {
fmt.Printf("failed to open file at path \"%s\": %s\n", b.path, err.Error())
return nil
return ErrOpenOptionalFile(fmt.Errorf("failed to open optional file at path \"%s\": %s", b.path, err.Error()))
}
return errors.Wrapf(err, "failed to open file at path \"%s\"", b.path)
}
Expand Down
17 changes: 17 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@ import (
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"reflect"
"strconv"
"strings"
"time"

"github.com/heetch/confita/backend"
"github.com/heetch/confita/backend/env"
"github.com/heetch/confita/backend/file"
)

// Loader loads configuration keys from backends and stores them is a struct.
Expand All @@ -21,6 +25,8 @@ type Loader struct {
// configuration keys and options.
// If empty, "config" is used.
Tag string

log *log.Logger
}

// Unmarshaler can be implemented by backends to receive the struct directly and load values into it.
Expand All @@ -37,6 +43,7 @@ type StructLoader interface {
func NewLoader(backends ...backend.Backend) *Loader {
l := Loader{
backends: backends,
log: log.New(ioutil.Discard, "[confita] ", log.LstdFlags),
}

if len(l.backends) == 0 {
Expand All @@ -46,6 +53,12 @@ func NewLoader(backends ...backend.Backend) *Loader {
return &l
}

// SetLoggerOutput is used for setting a writter for Confita's logger.
// By default, it logs to ioutil.Discard.
func (l *Loader) SetLoggerOutput(w io.Writer) {
l.log.SetOutput(w)
}

// Load analyses all the Fields of the given struct for a "config" tag and queries each backend
// in order for the corresponding key. The given context can be used for timeout and cancelation.
func (l *Loader) Load(ctx context.Context, to interface{}) error {
Expand Down Expand Up @@ -172,6 +185,10 @@ func (l *Loader) resolve(ctx context.Context, s *StructConfig) error {
if u, ok := b.(Unmarshaler); ok {
err := u.Unmarshal(ctx, s.S)
if err != nil {
if uerr, ok := err.(file.ErrOpenOptionalFile); ok {
l.log.Println(uerr.Error())
continue
}
return err
}

Expand Down

0 comments on commit a3c6fcb

Please sign in to comment.