Add AddFormatter function to allow custom builds to register new formatters

This commit is contained in:
Dan Jones 2026-03-09 16:11:53 -05:00
commit 17a1cf1ade
5 changed files with 60 additions and 31 deletions

View file

@ -2,18 +2,22 @@ package formatters
import (
"context"
"errors"
"fmt"
"sync"
"codeberg.org/danjones000/my-log/config"
"github.com/spf13/viper"
)
type formatMaker func(config *viper.Viper) (Formatter, error)
var mut sync.RWMutex
var formatterMap = map[string]formatMaker{
"plain": newPlain,
"json": newJson,
"zero": newNull,
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) {
@ -25,6 +29,8 @@ 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)
}
@ -34,8 +40,24 @@ func New(ctx context.Context, kind string) (f Formatter, err error) {
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
}