63 lines
1.2 KiB
Go
63 lines
1.2 KiB
Go
package formatters
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"sync"
|
|
|
|
"codeberg.org/danjones000/my-log/config"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
var mut sync.RWMutex
|
|
|
|
type FormatInit func(config *viper.Viper) (Formatter, error)
|
|
|
|
var formatterMap = map[string]FormatInit{
|
|
FormatPlain: newPlain,
|
|
FormatJSON: newJson,
|
|
FormatNull: newNull,
|
|
}
|
|
|
|
func Preferred(ctx context.Context) (f Formatter, err error) {
|
|
_, c := config.RetrieveFromContext(ctx)
|
|
return New(ctx, c.Formatters.Preferred)
|
|
}
|
|
|
|
func New(ctx context.Context, kind string) (f Formatter, err error) {
|
|
v, _ := config.RetrieveFromContext(ctx)
|
|
formatterConf := v.Sub("formatters." + kind)
|
|
|
|
mut.RLock()
|
|
defer mut.RUnlock()
|
|
if maker, ok := formatterMap[kind]; ok {
|
|
return maker(formatterConf)
|
|
}
|
|
|
|
return nil, fmt.Errorf("unimplemented format: %s", kind)
|
|
}
|
|
|
|
func Kinds() []string {
|
|
r := []string{}
|
|
|
|
mut.RLock()
|
|
defer mut.RUnlock()
|
|
for kind, _ := range formatterMap {
|
|
r = append(r, kind)
|
|
}
|
|
return r
|
|
}
|
|
|
|
var ErrAlreadyAdded = errors.New("formatter already present")
|
|
|
|
func AddFormatter(key string, f FormatInit) error {
|
|
mut.Lock()
|
|
defer mut.Unlock()
|
|
if _, present := formatterMap[key]; present {
|
|
return fmt.Errorf("%w: %s", ErrAlreadyAdded, key)
|
|
}
|
|
|
|
formatterMap[key] = f
|
|
return nil
|
|
}
|